10

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

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

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

2 回答 2

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。为了使这个工作,你必须创建另一个覆盖,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;
     }
 }

希望这个对你有帮助!

于 2012-02-21T18:52:12.747 回答
4

您想添加一个OverlayItemGoogle Mapview 教程展示了如何使用它。

于 2010-01-31T15:40:21.327 回答