Home » How to create onDoubleTap for Google Maps

postheadericon How to create onDoubleTap for Google Maps

If you are using the Google Maps within your app, you would like to have as much functionality as Google Maps it self offers. This is unfortunately not the case. You have to implement some stuff yourself. The double click/tap is one of these features which you have to implement yourself.

The basic principal is to use the GestureDetector for the detection of the appropriate gestures and event. I have decided to subclass the Overlay class (ZoomOverlay) containing the GestureDetector for the detecting of the events and a ZoomOnGestureListener class for the processing of the events. The ZoomOnGestureListener extends the GestureDetector.SimpleOnGestureListener so that we only need to override the methods we are interested in. You can place the GestureDetector inside the ZoomMapActivity class and let it implement the GestureDetector.OnDoubleTapListener and GestureDetector.OnGestureListener interface but this will make your code less readable and flexible in my opinion. The ZoomOverlay is added to the MapView within the OnCreate method of the ZoomMapActivity.

public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  setContentView(R.layout.mapview);

  mapView = (MapView)findViewById(R.id.mapView);
  mapView.getOverlays().add(new ZoomOverlay(getBaseContext(), mapView));
}

Within the ZoomOverlay constructor, the GestureDetector is created and initialized. The GestureDetector constructor takes the application context and a listener of the events. This listener is our ZoomOnGestureListener class.

public ZoomOverlay(Context context, MapView mapView) {
  gestureDetector = new GestureDetector(context,
  new ZoomOnGestureListener(mapView));
}

If we click or tap on the screen, the ZoomOverlay.onTouchEvent is called by the system. We pass the MotionEvent to the GestureDetector. The GestureDetector will detects if it is an event that we want or not.

public boolean onTouchEvent(MotionEvent motionEvent, MapView mapView) {
  return gestureDetector.onTouchEvent(motionEvent);
}

If it is a double click or tap, the ZoomOnGestureListener.onDoubleTap is called. Now, we can zoom in by calling the MapView.getController().zoomIn method.

public boolean onDoubleTap(MotionEvent e) {
  // Zoom in smoothly.
  mapView.getController().zoomIn();

  return true;
}

To make this application to run properly, the only thing left you have to do is place the Google Maps API key in the mapview.xml file. For more information about retrieving an API key click here. The full source code can be downloaded below and is created for Android 2.1 and above. Have fun and don't forget to like, plus or retweet if you like this blog.

The onDoubletap is used within the following apps:
- Tweet Live Wallpaper

Attachments:
Download this file (ZoomSampleGoogleMap.zip)ZoomSampleGoogleMap.zip17 Kb