使用BMap.InfoWindow,在for循环展示信息的时候,总是显示最后一条信息的数据。
其实,可以将BMap.InfoWindow的创建写在一个单独的function中。这样,每一个BMap.InfoWindow,就是显示的当条的信息。
这几天在写一个开发应用中,用到百度地图。功能要求将一批标记点加入地图,点击其中任意一个点,地图弹出InfoWindow框,里面显示与此点相关的内容。
按照常规写了如下代码:
var node = function(){ name; lng; lat; }; addmarks = function(nodes){ var _nodes = nodes; var _markers = new Array(); for(var i=0;i<_nodes.length;i++){ var _marker = new BMap.Marker(new BMap.Point(_nodes[i].lng, _nodes[i].lat)); var _node = _nodes[i]; var _html = "节点名:"+_node.name; _marker.addEventListener("click", function(e){ this.openInfoWindow(new BMap.InfoWindow(_html)); }); _marker.addEventListener("mouseover", function(e){ this.setTitle("坐标@ "+_node.lng+","+_node.lat); }); _markers.push(_marker); } myClusterer = new BMapLib.MarkerClusterer(myMap, {markers:_markers}); myClusterer.setMaxZoom(17); //myClusterer.setStyles(myStyles); };
addmarks = function(nodes){ var _nodes = nodes; var _markers = new Array(); for(var i=0;i<_nodes.length;i++){ var _html = "节点名:"+_node.name; shop_markers.push(createMark(_nodes[i], _html)); } myClusterer = new BMapLib.MarkerClusterer(myMap, {markers:shop_markers}); myClusterer.setMaxZoom(17); //myClusterer.setStyles(myStyles); }; createMark = function(node, info_html){ var _marker = new BMap.Marker(new BMap.Point(node.lng, node.lat)); _marker.addEventListener("click", function(e){ this.openInfoWindow(new BMap.InfoWindow(info_html)); }); _marker.addEventListener("mouseover", function(e){ this.setTitle("位于: "+node.lng+","+node.lat); }); return _marker; };
闭包的参考:
http://www.ruanyifeng.com/blog/2009/08/learning_javascript_closures.html
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures
或者 :
addmarks = function(nodes){ var _nodes = nodes; var _markers = new Array(); for(var i=0;i<_nodes.length;i++){ function(x){ var _html = "节点名:"+_node.name; shop_markers.push(createMark(_nodes[i], _html)); } myClusterer = new BMapLib.MarkerClusterer(myMap, {markers:shop_markers}); myClusterer.setMaxZoom(17); //myClusterer.setStyles(myStyles); }(i); };