【发布时间】:2017-03-17 02:59:03
【问题描述】:
我正在尝试为在此Google Map 上绘制的每个功能分配一个唯一 ID,然后使用rightclick 事件删除被点击的功能。目前所有功能都被删除,这是一个问题。
将特征添加到集合后,我会尝试分配唯一 ID:
var uniqueID = function() {
return ++currentID;
}
dataLayer.addListener('addfeature', savePolygon, function(event) {
event.feature.setProperty('featureID', uniqueID);
});
然后在rightclick 事件中,我想删除被点击的功能。我假设您需要为此步骤提供唯一的 ID,因此是前面的步骤。
dataLayer.addListener('rightclick', function() {
dataLayer.forEach(function(feature) {
dataLayer.remove(feature);
localStorage.removeItem('geoData');
});
});
完整代码如下。
JS:
var map;
var currentID = 0;
var uniqueID = function() {
return ++currentID;
}
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: -34.397,
lng: 150.644
},
zoom: 4,
// only show roadmap type of map, and disable ability to switch to other type
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
});
map.data.setControls(['Polygon']);
map.data.setStyle({
editable: true,
draggable: true
});
bindDataLayerListeners(map.data);
//load saved data
loadPolygons(map);
}
// Apply listeners to refresh the GeoJson display on a given data layer.
function bindDataLayerListeners(dataLayer) {
dataLayer.addListener('addfeature', savePolygon, function(event) {
event.feature.setProperty('featureID', uniqueID);
});
dataLayer.addListener('rightclick', function() {
dataLayer.forEach(function(feature) {
dataLayer.remove(feature);
localStorage.removeItem('geoData');
});
});
dataLayer.addListener('setgeometry', savePolygon);
}
function loadPolygons(map) {
var data = JSON.parse(localStorage.getItem('geoData'));
map.data.forEach(function(f) {
map.data.remove(f);
});
map.data.addGeoJson(data)
}
function savePolygon() {
map.data.toGeoJson(function(json) {
localStorage.setItem('geoData', JSON.stringify(json));
});
}
initMap();
原始来源:我从this thread 中的 JSFiddle 构建了这个示例。
【问题讨论】:
标签: javascript google-maps-api-3