2010-01-31 52 views
9

如何在地圖上的特定位置添加標記?在android中使用谷歌地圖添加標記在觸摸位置

我看到這個代碼顯示了觸摸位置的座標。我想要一個標記彈出或在每次觸摸時在同一位置顯示。我該怎麼做呢?

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

您想添加一個OverlayItemGoogle Mapview tutorial顯示如何使用它。

+0

oks!我知道了。我現在可以繪製標記。謝謝:) – lulala 2010-01-31 16:49:10

+0

好,你能接受答案,以便其他人想回答問題會知道這一個已經被回答了嗎? – RickNotFred 2010-01-31 18:23:08

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

我希望你有所幫助!