Thursday, September 1, 2011

Showing circle around a point in Android (Code)



I had been trying to draw circle around my GeoPoint on the maps. I came across several links, the only limitation in all of them was that i was not able to see my circle growing like Google maps and stuff when i zoom in my maps.

So, finally i had to do this....
Here is a reference for the same...  feel free to use it :)


 public MyOverlay(Drawable defaultMarker, Context context, GeoPoint gp) {
super(defaultMarker, context);
mContext = context;
globalGeoPoint = new GeoPoint(gp.getLatitudeE6(), gp.getLongitudeE6());
maxSizeAreaGP = new GeoPoint(gp.getLatitudeE6()+10000,
gp.getLongitudeE6());
}

private Context mContext;
private GeoPoint globalGeoPoint;
private GeoPoint maxSizeAreaGP;

@Override
public void draw(Canvas canvas, MapView mapV, boolean shadow) {
Projection projection = mapV.getProjection();
if (shadow && projection != null) {
Point pt = new Point();
projection.toPixels(globalGeoPoint, pt);
Point pt1 = new Point();
projection.toPixels(maxSizeAreaGP, pt1);
float circleRadius = (float)Math.sqrt(Math.pow(pt1.x-pt.x, 2)+Math.pow(pt1.y-pt.y, 2));
Paint circlePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
circlePaint.setColor(0x186666ff);
circlePaint.setStyle(Style.FILL_AND_STROKE);
canvas.drawCircle((float) pt.x, (float) pt.y, circleRadius,
circlePaint);
circlePaint.setColor(0xff6666ff);
circlePaint.setStyle(Style.STROKE);
canvas.drawCircle((float) pt.x, (float) pt.y, circleRadius,
circlePaint);
Bitmap markerBitmap = BitmapFactory.decodeResource(
getApplicationContext().getResources(), R.drawable.pin);
canvas.drawBitmap(markerBitmap, pt.x,
pt.y - markerBitmap.getHeight(), null);
super.draw(canvas, mapV, shadow);
}

You can use the above code to show blue circle on the map around a point which will be pan able...
The size of circle will increasing according to zoom level.

Let me know if its not working for you...

2 comments:

Anonymous said...

Excellent helped me a lot.. thanks a lot..

Unknown said...

Thanks for the code!

Don't suppose you can help me convert metres/miles to a latlng point so i can specify the radius.. im tearing my hair out here (rubbish at maths :( )

Thanks