簡體   English   中英

如何在Android中從Google Map v2清除圓圈和標記

[英]How to clear the circle and marker from the Google Map v2 in android

我想在位置更改后立即在android的Google Map v2上繪制一個以center為當前位置的圓。 現在,我所看到的是,每次更改位置時,圓都會不斷繪制(如果位置相同,則彼此重疊)而不會刪除前一個圓。 標記也發生了同樣的事情。

以下是我用來在Google Map v2上畫圓的代碼

@Override
public void onLocationChanged(Location location) {
    if (location != null) {

    // Create a LatLng object for the current location
    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());

    // Show the current location in Google Map
    map.moveCamera(CameraUpdateFactory.newLatLng(latLng));

    // Zoom in the Google Map
    map.animateCamera(CameraUpdateFactory.zoomTo(14));

    CircleOptions circleOptions = new CircleOptions().center(latLng) // set center
    .radius(1000) // set radius in meters
    .fillColor(Color.TRANSPARENT) // default
    .strokeColor(0x10000000).strokeWidth(5);

    myCircle = map.addCircle(circleOptions);

    map.addMarker(new MarkerOptions().position(latLng).title("You are here!"));
}

如何確定下一次繪制圓時,會從Google地圖中清除上一個圓和標記。 我需要在代碼中進行哪些更改?

任何幫助將不勝感激。

從地圖中刪除內容很簡單。 無論出於何種原因,在GoogleMaps v2中,您都無法簡單地通過獲取其ID來刪除Marker ,因為該值是在創建時自動生成的,因此幾乎沒有用處。 要解決此問題,您要做的就是創建可以存儲對要刪除的對象的引用的內容。 一種實現方法是創建HashMap並使用一些唯一的ID存儲對您的Marker ,圓或您想要刪除的其他任何內容的引用。 通過將對您放置在地圖上的事物的引用存儲在HashMap但是您可以在每次位置更新時調用與該鍵關聯的標記上的remove。 循環也是一樣(盡管如果按照下面的方式設置類型,您將需要不同的HashMap我不知道您是否可以使用將兩者存儲的通用String,Object映射)。

要使用此方法,請像實例變量一樣聲明HashMap以便可以從Activity所有方法中訪問它

private HashMap<String, Marker> mapStuff = new HashMap<String, Marker>();

然后,無論您在哪里創建Marker或其他地圖對象,只需將它們添加到具有某些鍵值的HashMap

Marker dude = map.addMarker(new MarkerOptions()
.position(newLatLng(latitude, longitude))
.title(MARKER_TITLE)
.snippet(SNIPPET));
mapStuff.put("userMarker", dude);

這個概念實際上與另一個發布者所建議的相同,后者只是將Marker作為實例變量並在其中存儲引用。 兩者都做同樣的事情。 如果您要處理多個標記或對象,則HashMap方法最有效。 如果只處理一個Marker或一個圓,則單變量方法可能更正確,因為您不需要使用“ Collection來添加或刪除一個標記。 只需聲明

private Marker userMarker;

然后在將Marker添加到地圖的位置存儲參考

userMarker = map.addMarker(new MarkerOptions()
.position(newLatLng(latitude, longitude))
.title(MARKER_TITLE)
.snippet(SNIPPET));

更新位置時,可能在onLocationChanged只需檢查標記的存在並將其刪除(如果存在)並重新添加

if(userMarker == null){
    displayUserMarker(location);
} else {
    userMarker.remove;
    displayUserMarker(location);
}
map.clear();

在if(location!= null)之前添加

這樣,每次位置更改時,所有標記和圓圈都會被刪除並再次繪制

首先,像繼續圈出一樣,保持對標記的引用

myMarker = map.addMarker(new MarkerOptions().position(latLng).title("You are here!"));

當您想刪除它們時,只需調用remove()

myCircle.remove();
myMarker.remove();

暫無
暫無

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

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