我想在用户单击复选框时显示或隐藏一些标记。我正在使用 Gmaps.js负责的代码是:
// Check if the user wants to display points of interest
$("#poi").click(function() {
var poi_markers = [];
if ($("#poi").is(':checked')) {
// Get points of interest and display them on the map
$.ajax({
type: "POST",
url: "/ajax/poi.php",
dataType: "JSON",
cache: false,
success: function(data) {
$.each(data, function(key, value) {
poi_marker = {
marker: {
lat: value.latitude,
lng: value.longitude,
icon: '/images/marker-sight.png',
infoWindow: {
content: value.name
}
}
}
poi_markers.push(poi_marker);
});
console.log(poi_markers);
map.addMarkers(poi_markers);
}
});
} else {
map.removeMarkers(poi_markers);
}
});
示例 JSON:
[{"name":"Biserica Neagra","latitude":"45.640981","longitude":"25.587723"}]
在 Firebug 中我得到这个错误:“未捕获的异常:没有定义纬度或经度。”。
我做错了什么?
最佳答案
问题 #1
addMarkers()
函数将标记数组作为参数。但是你给了它一个带有 marker 属性的对象数组。他们应该这样声明:
poi_marker = {
lat: value.latitude,
lng: value.longitude,
infoWindow: {
content: value.name
}
}
问题#2
removeMarkers()
函数不接受任何参数,因为它会删除所有标记。应该这样称呼:
map.removeMarkers();
如何只添加/删除标记组
为了清楚起见,并且因为我认为您会弄清楚如何执行此操作,所以我将省略 Ajax 部分,并假设您在收集标记后已将所有标记定义如下:
var realMarkers = {},
gMarkers = {
bars: [
{lat:"45.640981",lng:"25.587723",infoWindow:{content:"Irish Pub"}},
{lat:"45.645911",lng:"25.582753",infoWindow:{content:"Beer King"}}
],
transportation: [
{lat:"45.645981",lng:"25.590723",infoWindow:{content:"Subway"}},
{lat:"45.640981",lng:"25.583723",infoWindow:{content:"Train"}},
{lat:"45.636981",lng:"25.580723",infoWindow:{content:"Airport"}}
]
};
如您所见,我使用了对象 gMarkers
,其中 g 代表 Gmaps.js,因为这些标记与真实标记不同Google map 标记,您将需要这些标记。真正的标记将存储在 realMarkers
变量中。
由于 Gmaps.js 不提供仅添加/删除某些标记的方法,因此我创建了 2 个函数,您可以将它们添加到您的代码中。
addMarkersOfType()
/* Takes the poi type as a parameter */
GMaps.prototype.addMarkersOfType = function (poi_type) {
// clear markers of this type
realMarkers[poi_type]=[];
// for each Gmaps marker
for(var i=0; i<gMarkers[poi_type].length; i++){
// add the marker
var marker = map.addMarker(gMarkers[poi_type][i]);
// save it as real marker
realMarkers[poi_type].push(marker);
}
}
removeMarkersOfType()
/* Takes the poi type as a parameter */
GMaps.prototype.removeMarkersOfType = function (poi_type) {
// for each real marker of this type
for(var i=0; i<gMarkers[poi_type].length; i++){
// remove the marker
realMarkers[poi_type][i].setMap(null);
}
// clear markers of this type
realMarkers[poi_type]=[];
}
使用示例
$("#bar_poi").click(function() {
if ($(this).is(':checked'))
map.addMarkersOfType("bars");
else
map.removeMarkersOfType("bars");
});
JS Fiddle Demo
关于javascript - Gmaps.js 从数组中添加/删除标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24980094/