我整天都在修补这一点,似乎无法弄明白。当我渲染地图时,每次单击某个点时,它都会打开添加的最后一个位置的windowInfo。我已经验证了每个xml元素返回它的正确名称,位置,lat / lng等。任何帮助都将不胜感激。
<code>
<script type="text/javascript" src="//maps.googleapis.com/maps/api/js"></script>
<script>
$(document).ready(function () {
$("#map").css({
height: 300,
width: 400
});
var myLatLng = new google.maps.LatLng(33.985236, -117.715781);
MYMAP.init('#map', myLatLng, 8);
//alert("0: "+MYMAP.map.getZoom());
MYMAP.placeMarkers('/admin/company/project/googlexml');
//alert("2: "+MYMAP.map.getZoom())
});
var wh = $(document).height();
//$('#frame').height(wh - 125);
google.maps.visualRefresh = true;
var locations = 0;
var MYMAP = {
map: null,
bounds: null
}
MYMAP.init = function (selector, latLng, zoom) {
var myOptions = {
zoom: zoom,
center: latLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
this.map = new google.maps.Map($(selector)[0], myOptions);
this.bounds = new google.maps.LatLngBounds();
//alert("0: "+MYMAP.map.getZoom());
window.setTimeout(function () {
//alert("10: "+MYMAP.map.getZoom());
if (MYMAP.map.getZoom() > 13) {
MYMAP.map.setZoom(13)
}
}, 500);
}
MYMAP.placeMarkers = function (filename) {
$.post(filename, function (xml) {
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
//var image = '/images/someimage.png';
var lat = markers[i].getAttribute("lat");
var lng = markers[i].getAttribute("lng");
var point = new google.maps.LatLng(
parseFloat(lat),
parseFloat(lng)
);
//alert("data :" + name + " Address " + address + " lat/lng " + lat + ":" + lng);
locations++;
// extend the bounds to include the new point
MYMAP.bounds.extend(point);
var marker = new google.maps.Marker({
position: point,
map: MYMAP.map,
//icon: image,
clickable: true
});
marker.info = new google.maps.InfoWindow({
content: '<strong>' + name + '</strong><br />' + address
});
google.maps.event.addListener(marker, 'click', function () {
marker.info.open(MYMAP.map, marker);
});
MYMAP.map.fitBounds(MYMAP.bounds);
//alert("1: " + MYMAP.map.getZoom());
}
}, 'xml');
}
</code>
答案 0 :(得分:0)
在侦听器中对click事件使用“this”,“marker”仍然包含它在循环中的最后一个值:
google.maps.event.addListener(marker, 'click', function () {
this.info.open(MYMAP.map, marker);
});