Android: Double Taps on a MapView with Overlays

Download the source code for this post PushPin.tar.gz, PushPin.zip.

For the past few days, I’ve been struggling with the Android SDK to detect double-taps on a MapView with overlays. I’m working on Plymouth Software’s first Android app, which makes use of Google’s MapView class. The requirements are:

  • The map can have several pushpin markers overlaid onto it.
  • When the user double-taps an empty part of the map, a new pushpin is added at the tapped location.
  • When the user taps on an existing pushpin, they see a popup (or similar); no new marker is added.

Despite scouring the SDK and web for tutorials, I could only find examples of either detecting double taps (using primitive timers) or adding a list of markers which could be tapped. After several hours, I finally managed to get somewhere. Check out the call for help at the end of the post though!

Creating the Maps Activity

After creating a new Android project in the SDK, switch it to extend MapActivity and add a MapView to the layout. I’ve also setup the MapView with things like built-in zoom controls in the initialiseMapView() method:

<!-- /AndroidManifest.xml -->
 
  <!-- Required to use the Google Maps library -->
  <application>
    <!-- ... -->  
    <uses-library android:name="com.google.android.maps" />
  </application>
 
  <!-- Request permissions to access location and the internet -->
  <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
  <uses-permission android:name="android.permission.INTERNET" />
/* /src/com/example/PushPinActivity.java */
package com.example;
 
import android.graphics.drawable.Drawable;
import android.os.Bundle;
 
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.OverlayItem;
 
class PushPinActivity extends MapActivity {
  private MapView mapView;
  private MapController mapController;
 
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
 
    initialiseMapView();
  }
 
  @Override
  public boolean isRouteDisplayed() {
    return false;
  }
 
  private void initialiseMapView() {
    mapView = (MapView) findViewById(R.id.mapView);
    mapController = mapView.getController();
 
    mapView.setBuiltInZoomControls(true);
    mapView.setSatellite(false);
 
    GeoPoint startPoint = new GeoPoint((int)(40.7575 * 1E6), (int)(-73.9785 * 1E6));
    mapController.setCenter(startPoint);
 
    mapController.setZoom(8);
  }
}
<!-- /res/layout/main.xml -->
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <com.google.android.maps.MapView
    android:id="@+id/mapView"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:clickable="true"
    android:apiKey="YOUR_MAPS_API_KEY" />
</LinearLayout>

Adding Overlays

Next, I’ll add an array of Overlay markers to the map. I couldn’t find much high-level documentation on overlays, but from what I could figure out, the ItemizedOverlay class allows you to store a List of OverlayItems. Each OverlayItem is a marker on the map.

For this example, I’ve just used the default Android application icon as a marker. Let’s add a few Overlays in the initialiseOverlays() method, which is called from onStart() (not onCreate()). Note that I’ve also declared a property, placesItemizedOverlay which is a sub-class of ItemizedOverlay. The GeoPoint locations are from another tutorial I found during my research!

/* /src/com/example/PushPinActivity.java */
class PushPinActivity extends MapActivity {
  private PlacesItemizedOverlay placesItemizedOverlay;
 
  // ...
 
  @Override
  public void onStart() {
    super.onStart();
    initialiseOverlays();
  }
 
  private void initialiseOverlays() {
    // Create an ItemizedOverlay to display a list of markers
    Drawable defaultMarker = getResources().getDrawable(R.drawable.icon);
    placesItemizedOverlay = new PlacesItemizedOverlay(this, defaultMarker);
 
    placesItemizedOverlay.addOverlayItem(new OverlayItem(new GeoPoint((int) (40.748963847316034 * 1E6),
            (int) (-73.96807193756104 * 1E6)), "UN", "United Nations"));
    placesItemizedOverlay.addOverlayItem(new OverlayItem(new GeoPoint(
        (int) (40.76866299974387 * 1E6), (int) (-73.98268461227417 * 1E6)), "Lincoln Center",
        "Home of Jazz at Lincoln Center"));
    placesItemizedOverlay.addOverlayItem(new OverlayItem(new GeoPoint(
        (int) (40.765136435316755 * 1E6), (int) (-73.97989511489868 * 1E6)), "Carnegie Hall",
        "Where you go with practice, practice, practice"));
    placesItemizedOverlay.addOverlayItem(new OverlayItem(new GeoPoint(
        (int) (40.70686417491799 * 1E6), (int) (-74.01572942733765 * 1E6)), "The Downtown Club",
        "Original home of the Heisman Trophy"));
 
    // Add the overlays to the map
    mapView.getOverlays().add(placesItemizedOverlay);
  }
}
/* /src/com/example/PlacesItemizedOverlay.java */
package com.example;
 
import java.util.ArrayList;
 
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.drawable.Drawable;
 
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.OverlayItem;
 
public class PlacesItemizedOverlay extends ItemizedOverlay {
  private Context context;
  private ArrayList items = new ArrayList();
 
  public PlacesItemizedOverlay(Context aContext, Drawable marker) {
    super(boundCenterBottom(marker));
    context = aContext;
  }
 
    public void addOverlayItem(OverlayItem item) {
        items.add(item);
        populate();
    }
 
    @Override
    protected OverlayItem createItem(int i) {
        return items.get(i);
    }
 
    @Override
    public int size() {
        return items.size();
    }
 
    @Override
    protected boolean onTap(int index) {
      OverlayItem item = items.get(index);
      AlertDialog.Builder dialog = new AlertDialog.Builder(context);
      dialog.setTitle(item.getTitle());
      dialog.setMessage(item.getSnippet());
      dialog.show();
 
      return true;
    }
}

If you save and run the code now, you’ll see a map centred on Manhattan with several Android-esque markers scattered around. Tapping on one of the markers will popup an AlertDialog with the marker’s title and description. This is nothing more advanced than the standard Google reference documentation:

Android Markers

Detecting Double Taps

For my app, I needed to detect a double-tap anywhere else on the MapView, except where a Marker was displayed. To do this, I started to look at the GestureDetector class, and set about extending MapView to detect double-taps.

/* /src/com/example/PushPinMapView.java */
package com.example;
 
import android.content.Context;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.GestureDetector.OnGestureListener;
 
import com.google.android.maps.MapView;
 
public class PushPinMapView extends MapView {
  private Context context;
  private GestureDetector gestureDetector;
 
  public PushPinMapView(Context aContext, AttributeSet attrs) {
    super(aContext, attrs);
    context = aContext;
 
    gestureDetector = new GestureDetector((OnGestureListener)context);
    gestureDetector.setOnDoubleTapListener((OnDoubleTapListener) context);
  }
 
  // Override the onTouchEvent() method to intercept events and pass them
  // to the GestureDetector. If the GestureDetector doesn't handle the event,
  // propagate it up to the MapView.
  public boolean onTouchEvent(MotionEvent ev) {
    if(this.gestureDetector.onTouchEvent(ev))
       return true;
    else
      return super.onTouchEvent(ev);
  }
}
/* /src/com/example/PushPinActivity.java */
 
// ...
import android.view.GestureDetector.OnGestureListener;
import android.view.GestureDetector.OnDoubleTapListener;
 
class PushPinActivity extends MapActivity implements OnGestureListener, OnDoubleTapListener {
  // ...
 
  /**
   * Methods required by OnDoubleTapListener
   **/
  @Override
  public boolean onDoubleTap(MotionEvent e) {
    GeoPoint p = mapView.getProjection().fromPixels((int)e.getX(), (int)e.getY());
 
    AlertDialog.Builder dialog = new AlertDialog.Builder(this);
    dialog.setTitle("Double Tap");
    dialog.setMessage("Location: " + p.getLatitudeE6() + ", " + p.getLongitudeE6());
    dialog.show();
 
    return true;
  }
 
  @Override
  public boolean onDoubleTapEvent(MotionEvent e) {
    return false;
  }
 
  @Override
  public boolean onSingleTapConfirmed(MotionEvent e) {
    return false;
  }
 
  /**
   * Methods required by OnGestureListener
   **/
  @Override
  public boolean onDown(MotionEvent e) {
    return false;
  }
 
  @Override
  public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
    return false;
  }
 
  @Override
  public void onLongPress(MotionEvent e) {
  }
 
  @Override
  public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
    return false;
  }
 
  @Override
  public void onShowPress(MotionEvent e) {
  }
 
  @Override
  public boolean onSingleTapUp(MotionEvent e) {
    return false;
  }
}

Finally, make sure you change your main.xml layout file to use the com.example.PushPinMapView instead of the original Google version. This one caught me out whilst writing this post!

<!-- /res/layout/main.xml -->
  <!-- ....Change com.google.android.maps.MapView to use your custom MapView-->
  <com.example.PushPinMapView
    android:id="@+id/mapView"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:clickable="true"
    android:apiKey="YOUR_MAPS_API_KEY" />
  <!-- .... -->

What’s going on?

The custom PushPinMapView creates an instance of GestureDetector and dispatches any touch events (onTouchEvent()) to the designated OnGestureListener. In this code, that is the context instance of PushPinActivity.

If the listener handles the gesture (it’s a double-tap), it shouldn’t not propagate any further (see below). For any gestures that aren’t handled, the GestureDetector propagates the gesture up to other listeners. In this case, it would be handled by the parent MapView gesture handling, which means we don’t have to override things like dragging the map.

Also be sure that your OnGestureListener class imports from the android.view.GestureDetector package.

Call for help…

Whilst functional, the code is still not quite perfect. According to the documentation I’ve found on OnGestureListener, if a method returns true, then the event should not be propagated to any other listeners. However, despite onDoubleTap() returning true in the code above, you’ll find that if you double-tap on one of the OverlayItem markers, both the double-tap dialog and the marker’s dialog are displayed. It seems the MapView is detecting both a single and double-tap.

If you figure out how to stop double-taps on an OverlayItem from triggering a single tap event, please leave a comment and I’ll update the code in the post…Thanks!

Rails: Writing DRY Custom Validators

It is well know that Rails can quickly validate user input using validators such as validates_presence_of. What happens, though, when you need to write your own custom validations, whilst keeping things DRY?

Recently, I found a couple of duplicate validations in my code, and decided to DRY them up and implement my own custom validators in ActiveRecord. This post will guide you through that process.

Defining the Validator
We’ll build a custom validator to check that a model’s date attribute is set to a future date/time. Later, we’ll add configuration options to the validator. Here’s an example of how the final code might be used:

# Validates that +event_date+ is in the future
validates_is_after :event_date
 
# Validates that +ended_at+ is later than +started_at+
validates_is_after :ended_at, :after => :started_at

Mixing into ActiveRecord
To keep the code DRY, our validator should be available to any ActiveRecord::Base instance, so we’ll re-open the class definition and add our code:

# config/initializers/validators.rb
ActiveRecord::Base.class_eval do
  def self.validates_is_after(*attr_names)
    # todo: validation code
  end
end

Note: Most of the example code I found online put custom validator code into the lib folder, but I had more success following the Rails Guides site and creating a file under config/initializers, in this case called validators.rb

This code opens the ActiveRecord::Base class declaration, allowing us to add the new class method. All this is possible thanks to Ruby’s flexible mixins.

The single parameter attr_names uses the Ruby splat operator, examples of which can be found throughout Rails. In essence, the splat operator () lets us to pass any number of parameter values into the method, and packs them all into an array for us to use.

Building the Validator
Now that we’ve declared our validator, we need to write the validating code. First, though, it’s important to note the scope of our validation code. Remember that validates_is_after is a class method – so it has no access to the instance attributes, such as ends_at – that we want to validate. To get around this, Rails provides the validates_each block:

# config/initializers/validators.rb
ActiveRecord::Base.class_eval do
  def self.validates_is_after(*attr_names)
    validates_each(attr_names) do |record, attr_name, value|
      # validate each attribute
    end
  end
end

The block within validates_each will run for each attribute supplied to validates_is_after. Inside the block, record represents the current model (instance of ActiveRecord::Base), attr_name is the name of the attribute that is being validated, and value is the value of the attribute.

Next, we add the code that will validate each attribute is set to a value later the current time:

# config/initializers/validators.rb
...
def self.validates_is_after(*attr_names)
  validates_each(attr_names) do |record, attr_name, value|
    unless value.nil?
      record.errors.add(attr_name, 'must be after current time') if value < Time.now
    end
  end
end
...

We now have a working custom validator that you can call from any model object. Try adding a new model object with an :event_date attribute and adding the following validation:

class Event < ActiveRecord::Base
  validates_is_after :event_date
end
 
# /script/console
e = Event.new
e.event_date = 1.days.ago
 
e.valid?
=> false

Configuring the Validation
You can extend the validation method to take optional configuration parameters. For example, rather than just comparing against the current time, we might want the validator to check that a date is later than another given attribute, such as a :start_date.

This is achieved by making use of Rails’ extract_options! method. extract_options! returns the last item of an array if it is a Hash, otherwise it returns an empty Hash. Thus, we can supply any number of optional configuration values to the validator.

For now, add an optional configuration parameter called :after. If set, the comparison will be carried out against the value of :after rather than the current time. If is not set, :after will default to the current time:

# config/initializers/validators.rb
...
def self.validates_is_after(*attr_names)
  # Set the default configuration
  configuration = { :after => Time.now }
 
  # Update defaults with any supplied configuration values
  configuration.update(attr_names.extract_options!)
 
  # Validate each attribute, passing in the configuration
  validates_each(attr_names, configuration) do |record, attr_name, value|
    unless value.nil?
      if configuration[:after].is_a?(Time)
        after_date = configuration[:after]
      else
        after_date = record.send(configuration[:after])
      end
 
      unless after_date.nil?
        record.errors.add(attr_name, 'must be after ' + configuration[:after].to_s) if value < after_date
      end
    end
  end
end
...

Notice that we need to check if configuration[:after] is an instance of Time. If so, we compare the value with that of the current attribute. If configuration[:after] is not a Time, it should be another attribute, so we get its value from the record and compare against that.

We could, therefore, also supply :after with a time, e.g:

class Event < ActiveRecord::Base
  validates_is_after :ends_at, :after => 30.days.from_now
end

I hope this post helps you to develop your own ActiveRecord validators. I’m writing these guides as I learn more about Rails, so as always please feel free to comment below. If you spot some code in need of improvement, let me know and I’ll update accordingly. Thanks!