簡體   English   中英

Google Maps api v2 android:如何刪除單個標記?

[英]Google Maps api v2 android: How to Remove a single marker?

在我的應用中,我需要有兩種類型的標記:第一種需要停留在一個位置上,第二種需要移動,現在我還沒有靜態標記,但是如果手機變了,但是為此我打電話給mMap.clear(),我不想在位置改變時清除所有標記,所以我只需要刪除那個標記,我讀了另一個問題,我需要使用Marker.remove(); 刪除單個標記,但不確定在代碼中的哪里實現。

這是新位置的方法:

public void onLocationChanged(Location location) {
    mMap.clear();
    GetLatLong();
    handleNewLocation(location);
    mCurrentLocation = location;


}

這是handleNewLocation方法:

    private void handleNewLocation(Location location) {
    if (mLastLocation != null) {

        LatLng latLng = new LatLng(list.get(0), list.get(1));
        //mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));


        //añadir un nuevo marker con la posición de la variable latLng
        MarkerOptions camion = new MarkerOptions()
                .position(latLng)
                .title("Camión")
                .snippet("ruta " + ruta)
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.bus));


        Marker marker = mMap.addMarker(camion);
        if (marker == null) {
            mMap.addMarker(camion);
        } else {
            camion.position(latLng);

        }

    }
}

謝謝。

編輯:

List<Marker> markers = new ArrayList<Marker>();
@Override
public void onLocationChanged(Location location) {
    markers.clear();
    GetLatLong();
    handleNewLocation(location);
    mCurrentLocation = location;
}
private void handleNewLocation(Location location) {
    if (mLastLocation != null) {

        LatLng latLng = new LatLng(list.get(0), list.get(1));
        //mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));


        //añadir un nuevo marker con la posición de la variable latLng
        MarkerOptions camion = new MarkerOptions()
                .position(latLng)
                .title("Camión")
                .snippet("ruta " + ruta)
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.bus));


        Marker marker = mMap.addMarker(camion);

        if (marker == null) {

            markers.add(marker);
        } else {
            camion.position(latLng);

        }

    }
}

}

如果要刪除一個標記,則必須先記住該標記。 然后調用marker.remove()

碼:

class YourClass {
    Marker singleMarker; //marker to be removed

    public void addMarker() {
        ....
        //here you add your marker
        singleMarker = mMap.addMarker(camion);
    }

    public void removeSingleMarker() {
        if(singleMarker != null) {
            singleMarker.remove();
            singleMarker = null;
        }
    }
}

如上文所述,您可以嘗試將what-you-want-remove markerArrayListHashMap

樣例代碼:

// before loop:
List<Marker> markers = new ArrayList<Marker>();

// inside your loop:
Marker marker = myMap.addMarker(new MarkerOptions().position(new LatLng(geo1Dub,geo2Dub))); //...
markers.add(marker);

// after loop:
markers.size();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM