Android Geofencing with Google Maps
Join the DZone community and get the full member experience.
Join For Freea geofence is a virtual perimeter of interest that can be set up to fire notifications when it is entered or exited, or both. for example, a geofencing app can alert us that our kid has left a previously specified area, or send us a coupon (e.g. the "present this sms an get 20% off" offer type) when we happen to walk or drive in the proximity of a movie theater.
now, with the new location apis , google's location algorithm has been rewritten to be more accurate and use significantly less battery life. there is just enough documentation plus sample code and a downloadable sample app ( geofencedetection ) to help us get started creating geofencing apps. prerequisites are:
- download google play services (via android's sdk manager) and set it up as a library
- get a google maps v2 api key, and maybe run the sample app. this short quick start guide might help
- download (again via sdk manager) the support library to cater to older android versions.
for practical purposes, let's just start where the sample geofencing app ( geofencedetection ) stops, and introduce a few enhancements to make the app semi-decent and show a sample of possibilities with the new location api.
1. zoom and camera position
first, a little taste of google maps api v2. let's choose zoom level and camera angle:
import com.google.android.gms.maps.googlemap; import com.google.android.gms.maps.cameraupdatefactory; import com.google.android.gms.maps.model.cameraposition; import com.google.android.gms.maps.model.latlng; //... // inside class, for a given lat/lon cameraposition init = new cameraposition.builder() .target(new latlng(lat, lon)) .zoom( 17.5f ) .bearing( 300f) // orientation .tilt( 50f) // viewing angle .build(); // use googglemap mmap to move camera into position mmap.animatecamera( cameraupdatefactory.newcameraposition(init) );
the code above has a zoom level allowing the viewing of buildings in 3d. google maps v2 uses opengl for embedded systems ( opengl es v2) to render 2d and 3d computer graphics.
2. options menu
even if we are not big fans of an options menu, it might be adequate in this case, since we would not want to clutter the map with too much "touch" functionality (we will have plenty of that shortly).
we can toggle between "normal" and satellite view:
/** * toggle view satellite-normal */ public static void toggleview(){ mmap.setmaptype( mmap.getmaptype() == googlemap.map_type_normal ? googlemap.map_type_satellite : googlemap.map_type_normal); }
we can also provide a "flight mode", where we let the camera scroll away. not tremendously useful, but kind of cool nonetheless:
import com.google.android.gms.maps.googlemap.cancelablecallback; //... private static cancelablecallback callback = new cancelablecallback() { @override public void onfinish() { scroll(); } @override public void oncancel() {} }; public static void scroll() { // we don't want to scroll too fast since // loading new areas in map takes time mmap.animatecamera( cameraupdatefactory.scrollby(10, -10), callback ); // 10 pix }
3. geocoding/reverse geocoding
the sample is here to demonstrate features and makes heavy use of latitude/longitude coordinates. but we need to provide a more user-friendly way to interface with locations on the map, like a street address. we can use geocoding/reverse geocoding to transform a street address to coordinates and vice-versa using android's geocoder .
4. adding geofences
ok, now on to geofences. thanks to geocoding, we can request an actual physical address from the user instead of coordinates. we will just change that address to a latitude/longitude pair
internally
to process user input. notice how we use transparent uis as much as possible to enhance what some might call the user experience. notice also that we provide a spinner so that the user can choose between predefined values. that saves the user some typing and it saves us from validating coordinates values each time.
still, if we want to be even more user-friendly, we can give our users the possibility to pre-fill the address field by long-pressing a point on the map. we will then use reverse geocoding to translate the coordinates to a physical address for display (screen below on the right):
processing long-presses is pretty straightforward:
import com.google.android.gms.maps.googlemap.onmaplongclicklistener; //... public class mainactivity extends fragmentactivity implements onmaplongclicklistener { //... mmap.setonmaplongclicklistener(this); //... @override public void onmaplongclick(latlng point) { // reverse geocode point } }
adding /removing geofences is pretty much covered in the sample app (by the geofencerequester and geofenceremover classes). the thing to remember is that the process of adding/removing fences is as follows :
- a connection to google's location services is requested by our app.
- once/if the connection is available, the request to add/remove a fence is done using a pendingintent .
- if a similar request made by our app is still underway, the operation fails.
- although the method we call (e.g. addgeofences() ) returns at once, we won't know if the request was successful until location services calls back into our app (e.g. onaddgeofencesresultlistener 's onaddgeofencesresult() ) with a success status code.
- finally, the preceding method will use a broadcast intent to notify other components of our app of success/failure.
needless to say, we need to code defensively at almost every step of the way. now, once a geofence is added, we can add a marker (the default or a customized one) and choose between different shapes (circle, polygon, etc.) to delimit the geofence. for instance we can write this code to add the default marker and circle the fence within a specified radius:
import com.google.android.gms.maps.model.circle; import com.google.android.gms.maps.model.circleoptions; import com.google.android.gms.maps.model.markeroptions; //... public static void addmarkerforfence(simplegeofence fence){ if(fence == null){ // display en error message and return return; } mmap.addmarker( new markeroptions() .position( new latlng(fence.getlatitude(), fence.getlongitude()) ) .title("fence " + fence.getid()) .snippet("radius: " + fence.getradius()) ).showinfowindow(); //instantiates a new circleoptions object + center/radius circleoptions circleoptions = new circleoptions() .center( new latlng(fence.getlatitude(), fence.getlongitude()) ) .radius( fence.getradius() ) .fillcolor(0x40ff0000) .strokecolor(color.transparent) .strokewidth(2); // get back the mutable circle circle circle = mmap.addcircle(circleoptions); // more operations on the circle... }
here are the resulting screens, including the one we get once we "touch to edit" the info window:
the sample app has all we need to fire notifications once the circled area above is entered or exited. notice how we set up the marker's info window to allow editing the geofence radius, or removing the geofence altogether. to implement a clickable custom info window, all we need is to create our own infowindowadapter and oninfowindowclicklistener .
as for the notifications themselves, this is how they look like in the sample app:
we can of course change a notification's appearance and functionality, and... that would be the subject of another article. hopefully, this one gave a glimpse of what is possible with the new location api. have fun with android geofences.
Opinions expressed by DZone contributors are their own.
Comments