How do I add a marker on a particular location in the map?
I saw this code that shows the coordinates of the touched location. And I want a marker to pop or be shown in that same location every time it is touched. How do I do this?
public boolean onTouchEvent(MotionEvent event, MapView mapView) {
if (event.getAction() == 1) {
GeoPoint p = mapView.getProjection().fromPixels(
(int) event.getX(),
(int) event.getY());
Toast.makeText(getBaseContext(),
p.getLatitudeE6() / 1E6 + "," +
p.getLongitudeE6() /1E6 ,
Toast.LENGTH_SHORT).show();
mapView.invalidate();
}
return false;
}
To add a marker to a map, it is necessary create a new MarkerOptions object and then call the AddMarker method on a GoogleMap instance. This method will return a Marker object.
If you want to add a marker into the touched location, then you should do the following:
public boolean onTouchEvent(MotionEvent event, MapView mapView) {
if (event.getAction() == 1) {
GeoPoint p = mapView.getProjection().fromPixels(
(int) event.getX(),
(int) event.getY());
Toast.makeText(getBaseContext(),
p.getLatitudeE6() / 1E6 + "," +
p.getLongitudeE6() /1E6 ,
Toast.LENGTH_SHORT).show();
mapView.getOverlays().add(new MarkerOverlay(p));
mapView.invalidate();
}
return false;
}
Check that Im calling MarkerOverlay after the message appears. In order to make this works, you have to create another Overlay, MapOverlay:
class MarkerOverlay extends Overlay{
private GeoPoint p;
public MarkerOverlay(GeoPoint p){
this.p = p;
}
@Override
public boolean draw(Canvas canvas, MapView mapView,
boolean shadow, long when){
super.draw(canvas, mapView, shadow);
//---translate the GeoPoint to screen pixels---
Point screenPts = new Point();
mapView.getProjection().toPixels(p, screenPts);
//---add the marker---
Bitmap bmp = BitmapFactory.decodeResource(getResources(), /*marker image*/);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y-50, null);
return true;
}
}
I hope you find this useful!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With