DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How to Build a React Native Chat App for Android
  • Exploring Google's Open Images V7
  • The 12 Biggest Android App Development Trends in 2023
  • Android Cloud Apps with Azure

Trending

  • Artificial Intelligence, Real Consequences: Balancing Good vs Evil AI [Infographic]
  • Automatic Code Transformation With OpenRewrite
  • Integrating Security as Code: A Necessity for DevSecOps
  • A Complete Guide to Modern AI Developer Tools
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Deployment
  4. Android Geofencing with Google Maps

Android Geofencing with Google Maps

By 
Tony Siciliani user avatar
Tony Siciliani
·
Jun. 26, 13 · Tutorial
Likes (0)
Comment
Save
Tweet
Share
77.6K Views

Join the DZone community and get the full member experience.

Join For Free

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:

  1. download google play services (via android's sdk manager) and set it up as a library
  2. get a google maps v2 api key, and maybe run the sample app. this short quick start guide might help
  3. 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).

googlemaps-v2 options-menu

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):

add-fence-option add-fence-longtouch

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 :

  1. a connection to google's location services is requested by our app.
  2. once/if the connection is available, the request to add/remove a fence is done using  a pendingintent .
  3. if a similar request made by our app is still underway, the operation fails.
  4. 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.
  5. 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:

add-fence edit-fence

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:

notif3 notif2

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.

Google Maps Google (verb) Android (robot) app

Opinions expressed by DZone contributors are their own.

Related

  • How to Build a React Native Chat App for Android
  • Exploring Google's Open Images V7
  • The 12 Biggest Android App Development Trends in 2023
  • Android Cloud Apps with Azure

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!