我试图让用户最多删除10个标记,然后将其删除。当用户添加标记或拖动时,我还使用地图上标记的坐标更新“div”。除了当用户删除标记时,我已经完成了所有工作,当我遍历标记时,它似乎仍然在地图上。知道我做错了吗?
jsFiddle:jsfiddle.net/ryanverdel/WRyrJ/
代码:
$(document).ready(function () {
var markerCount = 0;
$("#test1").gmap3({
map: {
options: {
center: [-2.2214281090541204, -78.695068359375],
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
navigationControl: true,
scrollwheel: true,
disableDoubleClickZoom: true,
streetViewControl: false,
},
events: {
click: function (map, event) {
if(markerCount < 10){
$(this).gmap3(
{
marker: {
latLng: event.latLng,
options:{
draggable: true,
animation: google.maps.Animation.DROP,
},
events: {
click: function(marker) {
marker.setMap(map);
marker.setMap(null);
marker = null;
delete marker;
console.log(marker);
markerCount--;
},
dragend: function(marker) {
$("#inputArray").empty();
setTimeout(function(){
var markers = $("#test1").gmap3({
get: {
all: true
}
});
$.each(markers, function(i, marker){
$("#inputArray").append('<p>{"latitude":' + marker.position.lat() +', '+ '"longitude":' + marker.position.lng() +'},'+'</p>');
});
}, 400);
}
},
},
});
markerCount++;
$("#inputArray").empty();
setTimeout(function(){
var markers = $("#test1").gmap3({
get: {
all: true
}
});
$.each(markers, function(i, marker){
$("#inputArray").append('<p>{"latitude":' + marker.position.lat() +', '+ '"longitude":' + marker.position.lng() +'},'+'</p>');
});
}, 400);
}
else{
return false;
};
}
}
}
});
});
答案 0 :(得分:2)
这种事情在gmap3中可能不那么简单。与直接google.maps API相比,您需要略微不同的心态。
Thee main poitns:
clear
这是你的代码解开了一系列功能,并应用了必要的修复
$(document).ready(function () {
var mapOpts = {
center: [-2.2214281090541204, -78.695068359375],
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
navigationControl: true,
scrollwheel: true,
disableDoubleClickZoom: true,
streetViewControl: false,
};
function genId() {
return '' + (new Date()).getTime();
}
function addMarker(map, event) {
if (markerCount < 10) {
var uid = genId();
$(this).gmap3({
marker: {
latLng: event.latLng,
options: {
draggable: true,
animation: google.maps.Animation.DROP
},
events: {
click: function() {
clearMarker(uid);
},
dragend: listMarkers
},
id: uid
}
});
markerCount++;
listMarkers();
} else {
return false;
};
}
function listMarkers() {
$("#test1").gmap3({
get: {
all: true,
callback: function(results) {
$("#inputArray").empty();
$.each(results, function (i, marker) {
$("#inputArray").append('<p>{"latitude":' + marker.position.lat() + ', ' + '"longitude":' + marker.position.lng() + '},' + '</p>');
});
}
}
});
}
function clearMarker(uid) {
$('#test1').gmap3({
clear: {
id: uid,
callback: function() {
listMarkers();
markerCount--;
}
}
});
}
var markerCount = 0;
$("#test1").gmap3({
map: {
options: mapOpts,
events: {
click: addMarker
}
}
});
});
<强> DEMO 强>