lulala
lulala

Reputation: 647

Add marker on touched location using google map in Android

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;
}

Upvotes: 10

Views: 20293

Answers (2)

fergerm
fergerm

Reputation: 241

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!

Upvotes: 8

RickNotFred
RickNotFred

Reputation: 3401

You want to add an OverlayItem. The Google Mapview tutorial shows how to use it.

Upvotes: 4

Related Questions