Rehan Yousaf Rehan Yousaf - 2 months ago 28
Android Question

How to keep the map marker in the center of the screen at all times? Android

I am trying to find a way to center my map marker in my map fragment activity. So far, I have tried adding a marker to the center of the screen every time the map is moved i.e., the camera position is updated. But the problem with this solution is that every time a new marker gets added into the map at the center and the old one stays there so in just a couple of drags i would have like 10 markers on my screen. I tried using the clear method before adding the next marker but now the marker is just flashing too much. Here's my code:

mMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
@Override
public void onCameraChange(CameraPosition cameraPosition) {
LatLng location=mMap.getCameraPosition().target;
MarkerOptions marker=new MarkerOptions().position(location).title("");
mMap.clear();
mMap.addMarker(marker);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(location, 16));
}
});


The other solution i have found is to use a centered ImageView but the problem with that is that i want to change the icon of my marker. But when i add an image image to the image view, the center of the camera is in the green little circle in the center of this image and not the pointy end of it like i want to. Please help.

Answer

Don't use a real marker. Put the MapFragment or MapView in a layout with a fake marker image centered over it. When the location is chosen, place a real marker and hide the fake one.

If the "pointy end" of the fake marker image is not in its exact center, simply pad the image with transparent space until it is.