Add Marker on Android Google Map via touch or tap

shiteru picture shiteru · Jun 17, 2013 · Viewed 38.1k times · Source

I want to develop a Map Application using Google Map on Android. Now, I want to add marker on the map via Touch or Tap on the Map. How do I apply touch event to drop the marker on the map?

Answer

Sharanu picture Sharanu · Jun 17, 2013

Try using new Google Map API v2.

It's easy to use and you can add a marker on tap like this:

map.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
    @Override
    public void onMapClick(LatLng point) {
        allPoints.add(point);
        map.clear();
        map.addMarker(new MarkerOptions().position(point));
    }
});

or in Kotlin:

map.setOnMapClickListener {
    allPoints.add(it)
    map.clear()
    map.addMarker(MarkerOptions().position(it))
}

Note that you might want to remember all your added points in a list (allPoints), so you can re-draw or remove them later. An even better approach to remember the points would be to remember a Marker object for each of them - you can get the Marker object as a result from the addMarker function, it has a remove() function that easily removes the marker from the map.