I have a small android problem (google maps v2 api)
This is my code:
GoogleMaps mMap;
Marker marker = mMap.addMarker(new MarkerOptions().position(new LatLng(20, 20)));
I am trying to find a way to get the current screen coordinates (x,y) for this marker object.
Perhaps someone has an idea? I tried getProjection but it does not see to work.
Thanks! 🙂
Yes, use
Projectionclass. More specifically:Get
Projectionof the map:Get location of your marker:
Pass location to the
Projection.toScreenLocation()method:That’s all. Now
screenPositionwill contain the position of the marker relative to the top-left corner of the whole Map container 🙂Edit
Remember, that the
Projectionobject will only return valid values after the map has passed the layout process (i.e. it has validwidthandheightset). You’re probably getting(0, 0)because you’re trying to access position of the markers too soon, like in this scenario:Projectionof the map for marker positions on the screen.This is not a good idea since the the map doesn’t have valid width and height set. You should wait until these values are valid. One of the solutions is attaching a
OnGlobalLayoutListenerto the map view and waiting for layout process to settle. Do it after inflating the layout and initializing the map – for example inonCreate():Please read through the comments for additional informations.