Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 237
lulala Avatar asked Jan 31 '10 11:01

lulala


People also ask

Which of the following is the correct method to add a marker to a Google map object?

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.


1 Answers

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!

like image 104
fergerm Avatar answered Sep 22 '22 00:09

fergerm