当用户点击复选框时,我想显示或隐藏一些标记.我正在使用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中我收到此错误:"未捕获的异常:未定义纬度或经度.".
我究竟做错了什么?
该addMarkers()
函数将一组标记作为参数.但是你给它一个带有marker属性的对象数组.他们应该这样声明:
poi_marker = { lat: value.latitude, lng: value.longitude, infoWindow: { content: value.name } }
该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 Maps标记不同,您需要这些标记.真实的标记将存储在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"); });