75

I can't find an example on how to intercept the map touch on the new Google Maps API v2.

I need to know when the user touches the map in order to stop a thread (the centering of the map around my current location).

Trilarion
  • 9,318
  • 9
  • 55
  • 91
Gaucho
  • 1,298
  • 1
  • 17
  • 32
  • 3
    If someone answered your question, mark you question as answered. Also, you explicitly say 'clicks on the map', so no need to snap at ape or CommonsWare for not being able to read your mind. – Maarten Jan 17 '13 at 16:10
  • 1
    i could even mark it as answered but i wrote "map touch", not map "click". @ape in a comment suggested another thread that solves my problem ( http://stackoverflow.com/questions/13722869/how-to-handle-ontouch-event-for-map-in-google-map-api-v2 ) but i can't use it, as i wrote on comments. I can't get the solution on this thread neither on the linked one. Should i open another question? – Gaucho Jan 18 '13 at 18:39
  • your answer should be an answer, not edited into the question. You've made it really hard to follow. If your own answer is the one that helped you most, you can even accept it to show that for others. – Kate Gregory Jan 26 '13 at 15:40
  • i'm new to stackOverflow. i can do it! – Gaucho Jan 26 '13 at 16:08
  • [Why not implement `onCameraChange(CameraPosition position)`](http://developer.android.com/reference/com/google/android/gms/maps/GoogleMap.OnCameraChangeListener.html)? – dm78 Oct 06 '13 at 18:48
  • The camera changes (once or more) when the map is initially loaded, it's quite unreliable as there are onCameraChange calls even when the user doesn't touch the map. – Nima G Jul 23 '14 at 17:13
  • why don't you use CameraChangeListener? – Melbourne Lopes Feb 09 '15 at 09:47

11 Answers11

95

@ape wrote an answer here on how to intercept the map clicks, but I need to intercept the touches, and then he suggested the following link in a comment of its answer, How to handle onTouch event for map in Google Map API v2?.

That solution seems to be a possible workaround, but the suggested code was incomplete. For this reason I rewrote and tested it, and now it works.

Here it is the working code:

I created the class MySupportMapFragment.java

import com.google.android.gms.maps.SupportMapFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class MySupportMapFragment extends SupportMapFragment {
    public View mOriginalContentView;
    public TouchableWrapper mTouchView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
        mOriginalContentView = super.onCreateView(inflater, parent, savedInstanceState);
        mTouchView = new TouchableWrapper(getActivity());
        mTouchView.addView(mOriginalContentView);
        return mTouchView;
    }

    @Override
    public View getView() {
        return mOriginalContentView;
    }
}

I even created the class TouchableWrapper.java:

import android.content.Context;
import android.view.MotionEvent;
import android.widget.FrameLayout;

public class TouchableWrapper extends FrameLayout {

    public TouchableWrapper(Context context) {
        super(context);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {

        switch (event.getAction()) {

            case MotionEvent.ACTION_DOWN:
                  MainActivity.mMapIsTouched = true;
                  break;

            case MotionEvent.ACTION_UP:
                  MainActivity.mMapIsTouched = false;
                  break;
        }
        return super.dispatchTouchEvent(event);
    }
}

In the layout I declare it this way:

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
          android:id="@+id/mapFragment"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:layout_alignParentBottom="true"
          android:layout_below="@+id/buttonBar"
          class="com.myFactory.myApp.MySupportMapFragment"
/>

Just for test in the main Activity I wrote only the following:

public class MainActivity extends FragmentActivity {
    public static boolean mMapIsTouched = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}
Community
  • 1
  • 1
Gaucho
  • 1,298
  • 1
  • 17
  • 32
48

Here is a simple solution to get the location based on user selection (click option on map):

googleMap.setOnMapClickListener(new OnMapClickListener() {
  @Override
  public void onMapClick(LatLng arg0) {
    // TODO Auto-generated method stub
    Log.d("arg0", arg0.latitude + "-" + arg0.longitude);
  }
});
Sebastian Palma
  • 29,105
  • 6
  • 30
  • 48
Sampath Kumar
  • 4,015
  • 2
  • 24
  • 39
  • 3
    This process works when you touch on map smoothly but when you touch on maps more hardly and it start zooming, for this reason onMapClick method will not called. – Md. Sajedul Karim Nov 13 '15 at 19:35
  • 1
    @Md.SajedulKarim you can disable all gestures with googleMap.getUiSettings().setAllGesturesEnabled(false); and then listen to that tap, after re-enable the gestures. – Array Apr 04 '16 at 14:39
  • 2
    setOnMapClickListener does not recognize. What should I import? – ONE_FE Oct 12 '16 at 16:54
34

This feature and many more are now supported :)

this is the developer note(Issue 4636) :

The August 2016 release introduces a set of new camera change listeners for camera motion start, ongoing, and end events. You can also see why the camera is moving, whether it's caused by user gestures, built-in API animations or developer-controlled movements. For details, see the guide to camera change events: https://developers.google.com/maps/documentation/android-api/events#camera-change-events

Also, see the release notes: https://developers.google.com/maps/documentation/android-api/releases#august_1_2016

here is a code snippet from the documentation page

public class MyCameraActivity extends FragmentActivity implements
        OnCameraMoveStartedListener,
        OnCameraMoveListener,
        OnCameraMoveCanceledListener,
        OnCameraIdleListener,
        OnMapReadyCallback {

    private GoogleMap mMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_camera);

        SupportMapFragment mapFragment =
            (SupportMapFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap map) {
        mMap = map;

        mMap.setOnCameraIdleListener(this);
        mMap.setOnCameraMoveStartedListener(this);
        mMap.setOnCameraMoveListener(this);
        mMap.setOnCameraMoveCanceledListener(this);

        // Show Sydney on the map.
        mMap.moveCamera(CameraUpdateFactory
                .newLatLngZoom(new LatLng(-33.87365, 151.20689), 10));
    }

    @Override
    public void onCameraMoveStarted(int reason) {

        if (reason == OnCameraMoveStartedListener.REASON_GESTURE) {
            Toast.makeText(this, "The user gestured on the map.",
                           Toast.LENGTH_SHORT).show();
        } else if (reason == OnCameraMoveStartedListener
                                .REASON_API_ANIMATION) {
            Toast.makeText(this, "The user tapped something on the map.",
                           Toast.LENGTH_SHORT).show();
        } else if (reason == OnCameraMoveStartedListener
                                .REASON_DEVELOPER_ANIMATION) {
            Toast.makeText(this, "The app moved the camera.",
                           Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onCameraMove() {
        Toast.makeText(this, "The camera is moving.",
                       Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onCameraMoveCanceled() {
        Toast.makeText(this, "Camera movement canceled.",
                       Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onCameraIdle() {
        Toast.makeText(this, "The camera has stopped moving.",
                       Toast.LENGTH_SHORT).show();
    }
}
A.Alqadomi
  • 1,369
  • 2
  • 21
  • 28
9

I created an empty FrameLayout layered over top of the MapFragment in the layout. I then set an onTouchListener on this view so I know when the map has been touched but return false so that the touch gets passed on to the map.

<FrameLayout
    android:id="@+id/map_touch_layer"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

mapTouchLayer.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            Utils.logDebug(TAG, "Map touched!");
            timeLastTouched = System.currentTimeMillis();
            return false; // Pass on the touch to the map or shadow layer.
        }
    });
Flyview
  • 1,622
  • 1
  • 25
  • 39
7

https://developers.google.com/maps/documentation/android/reference/com/google/android/gms/maps/GoogleMap.OnMapClickListener

See this link. Implement the interface and fill in the onMapClick() method or whichever you need and set the onMapClickListener to the right implementation.

public class YourActivity extends Activity implements OnMapClickListener {
    @Override
    protected void onCreate(Bundle icicle) { 
        super.onCreate(icicle);
        ...
        my_map.setOnMapClickListener(this)        
        ...
    }

    public void onMapClick (LatLng point) {
        // Do Something
    }
}
ndsmyter
  • 6,221
  • 3
  • 20
  • 37
adarsh
  • 5,382
  • 4
  • 25
  • 47
  • Thank you very much ndsmyter for the answer. The onMapClick intercepts when you tap on the map, but it doesn't work when you move the finger on the map. I need to intercept not only the map click, but even the map pan. Do you know how to do? – Gaucho Dec 26 '12 at 13:42
  • 2
    Map Touch is not the "map Click", so the question is not answered. I need to intercept the map move due to user touch on the map and i can't find a working way to intercept this action. I think that i can't use the setOnCameraChangeListener cause i still use the animateCamera method to update the camera location in my code, then i just need a listener to intercept the touch on the map during the pan of the map. – Gaucho Dec 26 '12 at 15:00
  • I think you need the `onMarkerDragListener`? https://developers.google.com/maps/documentation/android/reference/com/google/android/gms/maps/GoogleMap.OnMarkerDragListener – adarsh Dec 26 '12 at 15:52
  • Dear @ape , the onMarkerDragListener intercepts the drag of a marker, not the pan of a map without markers. I need to get an interrupt when the user touch the map to pan. – Gaucho Dec 27 '12 at 10:38
  • @ndsmyter , i forgot to mention your name, could you please read my comments? thank you. – Gaucho Dec 27 '12 at 11:24
  • http://android-coding.blogspot.in/2011/08/detect-touch-on-mapview-ontapgeopoint-p.html Maybe this is useful? – adarsh Dec 27 '12 at 14:33
  • dear @ape, thank you for your reply but that is good only for api v.1 but it is deprecated. I'm using api v.2 – Gaucho Dec 27 '12 at 18:02
  • 2
    Okay I guess this helps? http://stackoverflow.com/questions/13722869/how-to-handle-ontouch-event-for-map-in-google-map-api-v2 – adarsh Dec 27 '12 at 19:06
  • that seems to be a possible workaround, i just can't write it down correctly. if you help me and write down the working code i give to you the solution. I wrote it down this way but i get errors on getActivity: public class MyMapFragment extends MapFragment{ public View mOriginalContentView; public TouchableWrapper mTouchView; @ Override public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) { mOriginalContentView = super.onCreateView(inflater, parent, savedInstanceState); mTouchView = new TouchableWrapper(getActivity()); ...continues.. – Gaucho Dec 29 '12 at 12:10
  • @Alexey Zakharov probably still solved the problem, cause approved the answer of your linked thread. – Gaucho Dec 29 '12 at 12:15
  • Perfect! Worked like a charm! At least for my use case. – Taslim Oseni Oct 01 '20 at 20:11
7

Gaucho has a great answer, and seeing the many upvotes I figured there might be some need for another implementation:

I needed it to use a listener so I can react on the touch and do not have to check it constantly.

I put all in one class that can be used like this:

mapFragment.setNonConsumingTouchListener(new TouchSupportMapFragment.NonConsumingTouchListener() {
    @Override
    public void onTouch(MotionEvent motionEvent) {
        switch (motionEvent.getActionMasked()) {
            case MotionEvent.ACTION_DOWN:
                // map is touched
                break;
            case MotionEvent.ACTION_UP:
                // map touch ended
                break;
            default:
                break;
            // use more cases if needed, for example MotionEvent.ACTION_MOVE
        }
    }
});

where the mapfragment needs to be of type TouchSupportMapFragment and in the layout xml this line is needed:

<fragment class="de.bjornson.maps.TouchSupportMapFragment"
...

Here is the class:

package de.bjornson.maps;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.google.android.gms.maps.SupportMapFragment;

public class TouchSupportMapFragment extends SupportMapFragment {
    public View mOriginalContentView;
    public TouchableWrapper mTouchView;
    private NonConsumingTouchListener mListener;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
        mOriginalContentView = super.onCreateView(inflater, parent, savedInstanceState);
        mTouchView = new TouchableWrapper(getActivity());
        mTouchView.addView(mOriginalContentView);
        return mTouchView;
    }

    @Override
    public View getView() {
        return mOriginalContentView;
    }

    public void setNonConsumingTouchListener(NonConsumingTouchListener listener) {
        mListener = listener;
    }

    public interface NonConsumingTouchListener {
        boolean onTouch(MotionEvent motionEvent);
    }

    public class TouchableWrapper extends FrameLayout {

        public TouchableWrapper(Context context) {
            super(context);
        }

        @Override
        public boolean dispatchTouchEvent(MotionEvent event) {
            if (mListener != null) {
                mListener.onTouch(event);
            }
            return super.dispatchTouchEvent(event);
        }
    }
}
Björn Kechel
  • 6,422
  • 2
  • 47
  • 49
2
  // Initializing
    markerPoints = new ArrayList<LatLng>();

    // Getting reference to SupportMapFragment of the activity_main
    SupportMapFragment sfm = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);

    // Getting Map for the SupportMapFragment
    map = sfm.getMap();

    // Enable MyLocation Button in the Map
    map.setMyLocationEnabled(true);

    // Setting onclick event listener for the map
    map.setOnMapClickListener(new OnMapClickListener() {

        @Override
        public void onMapClick(LatLng point) {

            // Already two locations
            if(markerPoints.size()>1){
                markerPoints.clear();
                map.clear();
            }

            // Adding new item to the ArrayList
            markerPoints.add(point);

            // Creating MarkerOptions
            MarkerOptions options = new MarkerOptions();

            // Setting the position of the marker
            options.position(point);


            if(markerPoints.size()==1){
                options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
            }else if(markerPoints.size()==2){
                options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
            }

            // Add new marker to the Google Map Android API V2
            map.addMarker(options);

            // Checks, whether start and end locations are captured
            if(markerPoints.size() >= 2){
                LatLng origin = markerPoints.get(0);
                LatLng dest = markerPoints.get(1);

            //Do what ever you want with origin and dest
            }
        }
    });
Pratibha Sarode
  • 1,583
  • 14
  • 16
2

I took the idea from the accepted answer and improved it by converting to Kotlin and adding constructors that allow the touchable wrapper to be declared in the markup, and using a settable callback property for the touch detection to remove the coupling directly to the activity which allows it to be reused more easily:

class TouchableWrapper : FrameLayout {

    constructor(context: Context) : this(context, null)
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)

    var onTouch: ((event :MotionEvent) -> Unit)? = null

    override fun dispatchTouchEvent(event: MotionEvent): Boolean {
        onTouch?.invoke(event)
        return super.dispatchTouchEvent(event)
    }
}

Then in your layout:

    <com.yourpackage.views.TouchableWrapper
        android:id="@+id/viewMapWrapper"
        android:layout_height="match_parent"
        android:layout_width="match_parent">
        <fragment
                  android:layout_width="match_parent"
                  android:layout_height="match_parent"
                  android:id="@+id/map"
                  tools:context=".MapsActivity"
                  android:name="com.google.android.gms.maps.SupportMapFragment"/>
    </com.yourpackage.views.TouchableWrapper>

Then setup your callback like this:

        findViewById<TouchableWrapper>(R.id.viewMapWrapper)
            .onTouch = {
            if (MotionEvent.ACTION_DOWN == it.action) {
                  //Handle touch down on the map
            }
        }
Ian Newson
  • 101
  • 2
1

For Mono lovers:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Util;
using Android.Views;
using Android.Widget;
using Android.Gms.Maps;

namespace apcurium.MK.Booking.Mobile.Client.Controls
{
    public class TouchableMap : SupportMapFragment
    {
        public View mOriginalContentView;

        public TouchableWrapper Surface;

        public override View OnCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState)
        {
            mOriginalContentView = base.OnCreateView(inflater, parent, savedInstanceState);
            Surface = new TouchableWrapper(Activity);
            Surface.AddView(mOriginalContentView);
            return Surface;
        }

        public override View View
        {
            get
            {
                return mOriginalContentView;
            }
        }
    }

    public class TouchableWrapper: FrameLayout {

        public event EventHandler<MotionEvent> Touched;

        public TouchableWrapper(Context context) :
        base(context)
        {
        }

        public TouchableWrapper(Context context, IAttributeSet attrs) :
        base(context, attrs)
        {
        }

        public TouchableWrapper(Context context, IAttributeSet attrs, int defStyle) :
        base(context, attrs, defStyle)
        {
        }

        public override bool DispatchTouchEvent(MotionEvent e)
        {
            if (this.Touched != null)
            {
                this.Touched(this, e);
            }

            return base.DispatchTouchEvent(e);
        }
    }
}
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Léon Pelletier
  • 2,490
  • 2
  • 34
  • 64
1

I have a more simple solution diferent to the TouchableWrapper and this works with the last version of play-services-maps:10.0.1. This solution only uses the maps events and does not use custom views. Does not uses deprecated functions and will likely have support for several versions.

First you need a flag variable that stores if the map is being moved by an animation or by user input (this codes asumes that every camera move that is not triggered by an animation is triggered by the user)

GoogleMap googleMap;
boolean movedByApi = false;

Your fragament or activity must implement GoogleMap.OnMapReadyCallback, GoogleMap.CancelableCallback

public class ActivityMap extends Activity implements OnMapReadyCallback, GoogleMap.CancelableCallback{
    ...
}

and this forces you to implement the methods onMapReady, onFinish, onCancel. And the googleMap object in onMapReady must set an eventlistener for camera move

@Override
public void onMapReady(GoogleMap mMap) {
    //instantiate the map
    googleMap = mMap;

    [...]  // <- set up your map

    googleMap.setOnCameraMoveListener(new GoogleMap.OnCameraMoveListener() {
        @Override
        public void onCameraMove() {
            if (movedByApi) {
                Toast.makeText(ActivityMap.this, "Moved by animation", Toast.LENGTH_SHORT).show();

                [...] // <-- do something whe you want to handle api camera movement
            } else {
                Toast.makeText(ActivityMap.this, "Moved by user", Toast.LENGTH_SHORT).show();

                [...] // <-- do something whe you want to handle user camera movement
            }
        }
    });
}
@Override
public void onFinish() {
    //is called when the animation is finished
    movedByApi = false;
}
@Override
public void onCancel() {
    //is called when the animation is canceled (the user drags the map or the api changes to a ne position)
    movedByApi = false;
}

And finally its beter if you create a generic function for moving the map

public void moveMapPosition(CameraUpdate cu, boolean animated){
    //activate the flag notifying that the map is being moved by the api
    movedByApi = true;
    //if its not animated, just do instant move
    if (!animated) {
        googleMap.moveCamera(cu);
        //after the instant move, clear the flag
        movedByApi = false;
    }
    else
        //if its animated, animate the camera
        googleMap.animateCamera(cu, this);
}

or just every time you move the map, activate the flag before the animation

movedByApi = true;
googleMap.animateCamera(cu, this);

I hope this helps!

Sander Rito
  • 376
  • 2
  • 8
0

@Gaucho MySupportMapFragment will obviously be used by some other fargment or activity(where there might be more view elements than the map fragment). So how can one dispatch this event to the next fragment where it is to be used. Do we need to write an interface again to do that?