A 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:
01.
import
com.google.android.gms.maps.GoogleMap;
02.
import
com.google.android.gms.maps.CameraUpdateFactory;
03.
import
com.google.android.gms.maps.model.CameraPosition;
04.
import
com.google.android.gms.maps.model.LatLng;
05.
//...
06.
// inside class, for a given lat/lon
07.
CameraPosition INIT =
08.
new
CameraPosition.Builder()
09.
.target(
new
LatLng(lat, lon))
10.
.zoom( 17.5F )
11.
.bearing( 300F)
// orientation
12.
.tilt( 50F)
// viewing angle
13.
.build();
14.
// use GooggleMap mMap to move camera into position
15.
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:
01.
/**
02.
* Toggle View Satellite-Normal
03.
*/
04.
public
static
void
toggleView(){
05.
mMap.setMapType( mMap.getMapType() ==
06.
GoogleMap.MAP_TYPE_NORMAL ?
07.
GoogleMap.MAP_TYPE_SATELLITE :
08.
GoogleMap.MAP_TYPE_NORMAL);
09.
}
We can also provide a “Flight Mode”, where we let the camera scroll away. Not tremendously useful, but kind of cool nonetheless:
01.
import
com.google.android.gms.maps.GoogleMap.CancelableCallback;
02.
//...
03.
private
static
CancelableCallback callback =
new
CancelableCallback() {
04.
@Override
05.
public
void
onFinish() {
06.
scroll();
07.
}
08.
@Override
09.
public
void
onCancel() {}
10.
};
11.
12.
public
static
void
scroll() {
13.
// we don't want to scroll too fast since
14.
// loading new areas in map takes time
15.
mMap.animateCamera( CameraUpdateFactory.scrollBy(10, -10),
16.
callback );
// 10 pix
17.
}
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.
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.
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:
01.
import
com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
02.
//...
03.
public
class
MainActivity
extends
FragmentActivity
04.
implements
OnMapLongClickListener {
05.
//...
06.
mMap.setOnMapLongClickListener(
this
);
07.
//...
08.
@Override
09.
public
void
onMapLongClick(LatLng point) {
10.
// reverse geocode point
11.
}
12.
}
Adding /Removing geofences is pretty much covered in the sample app (by the GeofenceRequesterand 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 aPendingIntent.
- 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:
01.
import
com.google.android.gms.maps.model.Circle;
02.
import
com.google.android.gms.maps.model.CircleOptions;
03.
import
com.google.android.gms.maps.model.MarkerOptions;
04.
//...
05.
public
static
void
addMarkerForFence(SimpleGeofence fence){
06.
if
(fence ==
null
){
07.
// display en error message and return
08.
return
;
09.
}
10.
mMap.addMarker(
new
MarkerOptions()
11.
.position(
new
LatLng(fence.getLatitude(), fence.getLongitude()) )
12.
.title(
"Fence "
+ fence.getId())
13.
.snippet(
"Radius: "
+ fence.getRadius()) ).showInfoWindow();
14.
15.
//Instantiates a new CircleOptions object + center/radius
16.
CircleOptions circleOptions =
new
CircleOptions()
17.
.center(
new
LatLng(fence.getLatitude(), fence.getLongitude()) )
18.
.radius( fence.getRadius() )
19.
.fillColor(0x40ff0000)
20.
.strokeColor(Color.TRANSPARENT)
21.
.strokeWidth(2);
22.
23.
// Get back the mutable Circle
24.
Circle circle = mMap.addCircle(circleOptions);
25.
// more operations on the circle...
26.
27.
}
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 ownInfoWindowAdapter 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.
No comments:
Post a Comment