从 GoogleMap 中删除标记 [英] Remove a marker from a GoogleMap
问题描述
在适用于 Android 的新 Google Maps API 中,我们可以添加标记,但没有办法(轻松)删除一个.
In the new Google Maps API for Android, we can add a marker, but there is no way to (easily) remove one.
我的解决方案是将标记保留在地图中,并在我想删除标记时重新绘制地图,但效率不高.
My solution is to keep the markers in a map and redraw the map when I want to remove a marker, but it is not very efficient.
private final Map<String, MarkerOptions> mMarkers = new ConcurrentHashMap<String, MarkerOptions>();
private void add(String name, LatLng ll) {
final MarkerOptions marker = new MarkerOptions().position(ll).title(name);
mMarkers.put(name, marker);
runOnUiThread(new Runnable() {
@Override
public void run() {
mMap.addMarker(marker);
}
});
}
private void remove(String name) {
mMarkers.remove(name);
runOnUiThread(new Runnable() {
@Override
public void run() {
mMap.clear();
for (MarkerOptions item : mMarkers.values()) {
mMap.addMarker(item);
}
}
});
}
有没有人有更好的主意?
Does anyone have a better idea?
推荐答案
addMarker
是:
public final Marker addMarker (MarkerOptions options)
因此,当您通过指定标记选项将标记添加到 GoogleMap
时,您应该保存 Marker
返回的对象(而不是您用来创建它的 MarkerOptions
对象).此对象允许您稍后更改标记状态.完成标记后,您可以调用 Marker.remove()
将其从地图中删除.
So when you add a marker to a GoogleMap
by specifying the options for the marker, you should save the Marker
object that is returned (instead of the MarkerOptions
object that you used to create it). This object allows you to change the marker state later on. When you are finished with the marker, you can call Marker.remove()
to remove it from the map.
顺便说一句,如果您只想暂时隐藏它,您可以通过调用 Marker.setVisible(boolean)
.
As an aside, if you only want to hide it temporarily, you can toggle the visibility of the marker by calling Marker.setVisible(boolean)
.
这篇关于从 GoogleMap 中删除标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!