I am working on an Android application using the Gooogle Maps v2 API. I have markers on my map and I would like to surround one of them. I did this easily using the Circle and Circle Options classes. But I would also like my circle to keep the same size on the screen when zoomed in or out, just like markers. This means that the circle must have a constant radius in pixels. Unfortunately, we cannot set the radius in pixels in API v2.
I tried several solutions, but I am not satisfied.
In the first, I just multiply or divide the radius:
@Override public void onCameraChange(CameraPosition position) { if(previousZoom > position.zoom) { mSelectionCircle.setRadius(Math.abs(position.zoom - previousZoom)*2*mSelectionCircle.getRadius()); } else if(previousZoom < position.zoom) { mSelectionCircle.setRadius(Math.abs(position.zoom - previousZoom)*mSelectionCircle.getRadius()/2); } previousZoom = position.zoom; }
This seemed to work at first, but leads to incorrect results when scaling quickly or scaling with your fingers. In addition, scaling is clearly visible on the screen.
My second solution uses pixel meter conversions. The idea is to recalculate the radius in meters when scaling / zooming, so the circle has a constant size on the screen. To do this, I get the current position of the circle on the screen:
Point p1 = mMap.getProjection().toScreenLocation(mSelectionCircle.getCenter());
Then I create another point located on the edge of the circle:
Point p2 = new Point(p1.x + radiusInPixels, p1.y);
Where
int radiusInPixels = 40;
After that, I use a function that returns the distance between these two points in meters.
private double convertPixelsToMeters(Point point1, Point point2) { double angle = Math.acos(Math.sin(point1.x) * Math.sin(point2.x) + Math.cos(point1.x) * Math.cos(point2.x) * Math.cos(point1.y- point2.y)); return angle * Math.PI * 6378100.0;
6378100 - the average radius of the Earth. Finally, I set a new circle radius:
mSelectionCircle.setRadius(convertPixelsToMeters(p1, p2));
It should work theoretically, but I get ridiculous values for the radius (10 ^ 7 m!). Can the conversion function be wrong?
So, is there an easier way to do this, or if not, can you help me understand why my second soloeton is not working?
Thanks!