[在Android中使用Google地图在触摸的位置添加标记

问题描述 投票:10回答:2

如何在地图上的特定位置添加标记?

我看到了这段显示触摸位置坐标的代码。我希望每次触摸标记时都将其弹出或显示在同一位置。我该怎么做?

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;
}
android google-maps google-maps-markers
2个回答
4
投票

您要添加OverlayItemGoogle Mapview tutorial显示如何使用它。


8
投票

如果要在触摸的位置添加标记,则应执行以下操作:

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

出现此消息后,请检查我是否正在调用MarkerOverlay。为了使它起作用,您必须创建另一个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;
     }
 }

希望您觉得这有用!

© www.soinside.com 2019 - 2024. All rights reserved.