2016-03-15 67 views
-1

我只需要加載google map上的兩個標記,但加載了多個標記。Android上的Google地圖上只加載兩個標記

下面是我的代碼:

public class MainActivity extends FragmentActivity { 
     GoogleMap map; 

     @Override 
     protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     // Getting reference to SupportMapFragment of the activity_main 
     SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); 

     // Getting Map for the SupportMapFragment 
     map = fm.getMap(); 

     if (map != null) { 

      // Enable MyLocation Button in the Map 
      if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != 
                PackageManager.PERMISSION_GRANTED 
                && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != 
                PackageManager.PERMISSION_GRANTED) { 
       return; 
      } 
      map.setMyLocationEnabled(true); 

      //It is used to zoom when google first loading on your device. 
      map.setMapType(GoogleMap.MAP_TYPE_NORMAL); 
      map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(23.0310791, 72.5954376), 11)); 
      map.setMyLocationEnabled(true); 
      map.animateCamera(CameraUpdateFactory.zoomTo(11));    
     } 

     map.setOnMapClickListener(new GoogleMap.OnMapClickListener() { 
      @Override 
      public void onMapClick(LatLng latLng) { 

       // Creating a marker 
       MarkerOptions markerOptions = new MarkerOptions(); 

       // Setting the position for the marker 
       markerOptions.position(latLng); 

       // Placing a marker on the touched position 
       map.addMarker(markerOptions); 

      } 
     }); 
    } 
} 

我已實施google map API加載地圖,上面就是我試圖加載標記。它根據提供的緯度和長度加載標記,但我需要在我的谷歌地圖上只繪製兩個標記。

+1

當有人點擊地圖時,您已添加標記。所以你點擊它的次數就會被放在地圖上。所以當你放置一個新的標記時你想刪除上一個標記嗎? –

+0

檢查這個答案,如果它適用於你http://stackoverflow.com/a/35770711/3514144 –

回答

1

我認爲是,在地圖上放置2個標記,並在每個地圖上不斷更改那裏的位置點擊重要:爲舊標記設置新位置。

map.setOnMapClickListener(new GoogleMap.OnMapClickListener() { 
     boolean swap; 
     Marker firstMarker = null, secondMarker = null; 
     @Override 
     public void onMapClick(LatLng latLng) { 

      if (firstMarker == null) { 
       MarkerOptions options = new MarkerOptions(); 
       options.position(latLng); 
       firstMarker = map.addMarker(options); 
       return; 
      } 

      if (secondMarker == null) { 
       MarkerOptions options = new MarkerOptions(); 
       options.position(latLng); 
       secondMarker = map.addMarker(options); 
       return; 
      } 
      swap = !swap; 
      if (swap) { 
       firstMarker.setPosition(latLng); 
      } else { 
       secondMarker.setPosition(latLng); 
      } 
     } 
    }); 

Happy_Coding;

+0

謝謝Bharat它工作正常。 –

相關問題