Share the post "How To Create A Smooth Circular PolyLineOptions In Android Maps V2"
So I created a set of LatLng objects and passed them to the PolylineOptions object in an Android Google Map and saw the resulting shape as a circle.
But the problem was the edges are not smooth. When I zoom in to the map, the circular shaped PolyLine looks good. However, when I zoom out, the smallest circle I had looked like an octagon.
So how to we go about creating a smooth circular PolyLine shape in Android Maps v2?
The only way to accomplish this is to make use of Android Map Utils CircleOptions. Just pass in a center LatLng object and the radius and voila! A smooth circle Polyline shape.
To get the center point of a set of LatLng objects, you need to pass all of them to a LatLngBounds object.
|
1 2 3 4 5 6 7 8 |
ArrayList<LatLng> points = ...; LatLngBounds.Builder builder = new LatLngBounds.Builder(); for (LatLng ll : points) { builder.include(ll); } LatLngBounds bounds = builder.build(); |
Once you have the LatLngBounds object, you can easily get the center point by calling getCenter(). The LatLngBounds class also has a variable called northeast that returns a LatLng object representing the north east point of the bounds.
What you need to do then is to get the distance between these 2 points which we will use as the radius of the circle.
We can accomplish this by placing the 2 LatLng points inside a Location object and calling the Location class’ distanceTo() method.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
LatLng center = bounds.getCenter(); LatLng northEast = bounds.northeast; Location l1 = new Location(""); l1.setLatitude(center.latitude); l1.setLatitude(center.longitude); Location l2 = new Location(""); l2.setLatitude(northEast.latitude); l2.setLatitude(northEast.longitude); double distance = l1.distanceTo(l2); |
That’s it! Add the LatLng center object to the CircleOptions class and set the distance as the radius of the circle.
|
1 |
googleMap.addCircle(new CircleOptions().center(center).radius(distance)); |
Now you have a smooth well shaped circle no matter what zoom level your Google map is in.