I've an Android Application that displays a map. The map is by default centered on the user position following its movements (the center is updated according to the position updates).
However I want the user to be able to use gestures to navigate throw the map. When the user starts the navigation I want the "following" to stop, and a button is displayed so that it can start again.
How can I know when the user has moved the map center? On the GoogleMap.OnCameraChangeListener, I don't know if the change is due to a location changed or a user interaction. I've a a kind of working solution using the OnCameraChangeListener, but its a bit "dirty" and I don't find it very nice:
map.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
@Override
public void onCameraChange(CameraPosition position) {
// gpsPosition contains the last position obtained
if(isFollowing && gpsPosition!=null && (Math.abs(position.target.latitude - gpsPosition.latitude)>0.000001 || Math.abs(position.target.longitude - gpsPosition.longitude)>0.000001) ){
isFollowing = false;
map.getUiSettings().setMyLocationButtonEnabled(true);
}
}
});
Is there a nice Solution to the problem?
If you want to detect user interacting with the map OnCameraChangeListener
is surely too late to do that. It may be called seconds after user started interacting with the map.
What you need to do, is add 2 other listeners:
OnMyLocationButtonClickListener
- to know when to start tracking (set your isFollowing
to true
)OnMyLocationChangeListener
- when your isFollowing
is true
, call GoogleMap.animateCamera
to the new positionSo the only thing left is when you set isFollowing
to false
:
Create an invisible overlay in your layout (like here, but with normal View
instead of custom) and assign this overlay (the View
) an OnTouchListener
(ok, it is 3rd, I lied that you need only 2).
In this listener always return false
, but also set isFollowing
to false
. This when when user starts interacting with the map and you should stop automated camera movements.
I also see you are showing and hiding my location button, so do this where you change the value of isFollowing
. Btw.: good idea to do that. I'll try it too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With