Christophe Longeanie - 3 months ago 35

Android Question

I'm working on an Android Application using Gooogle Maps API v2. I have markers on my map, and I'd like to circle one of them. I managed to do that easily, by using the Circle and Circle Options classes. But I'd also like my circle to keep the same size on the screen when zooming or unzooming, just like the markers do. It means that the circle must have a constant radius in terms of pixels. Sadly, we cannot set a radius in pixels in the API v2.

I have tried several solutions, but I'm not satisfied.

In the first one, 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;

}

It seemed to work at first, but produces wrong results when zooming quickly or zooming with fingers. Moreover, the scaling is clearly visible on the screen.

My second solution uses pixel-meter conversions. The idea is to recalculate the radius in meters when zooming/unzooming, so the circle has a constant size on the screen. To do that, I get the current position of the Circle on the screen:

`Point p1 = mMap.getProjection().toScreenLocation(mSelectionCircle.getCenter());`

Then I create another point which is 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 which 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; // distance in meters

}

6378100 is average Earth radius. Finally, I set the new radius of the Circle :

`mSelectionCircle.setRadius(convertPixelsToMeters(p1, p2));`

It should work in theory but I get ridiculous radius values (10^7 m!). The conversion function may be wrong?

So is there a simpler method to do that, or if not, may you help me to understand why my second soluton doesn't work?

Thanks!

Answer

Use a custom icon for `Marker`

instead. You can create `Bitmap`

and `Canvas`

, draw on the latter and use it as a `Marker`

icon:

```
new MarkerOptions().icon(BitmapDescriptorFactory.fromBitmap(bitmap))...
```

Source (Stackoverflow)

Comments