[英]Trouble displaying an array of markers on Google Maps v3
我编写了一个简短的脚本来获取一系列位置对象(由PHP生成)并将其绘制在Google Map上。
为了我的一生,我无法弄清楚为什么addMarker()
循环会中断?
我要发送给initializeMap()
的数组的示例:
[
{
date: '08/11/2011',
venue: 'Notes',
city: 'Newtown, NSW',
ticket: 'http://noteslive.net.au/'
}
]
和代码:
// Accepts an array of gigs
function initializeMap(gigs) {
var markers = gigs;
// Create geocoder
var geocoder = new google.maps.Geocoder();
// Create the map
var map = new google.maps.Map(document.getElementById("gigpress-map"), {
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// Create infowindow object
var infowindow = new google.maps.InfoWindow({
content: "holding..."
});
// Add markers to map
for (index in markers) addMarker(markers[index]);
function addMarker(data) {
alert('bang');
geocoder.geocode( { 'address': data.city}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker( {
position: results[0].geometry.location,
map: map,
title: data.venue
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
// Bind click event to each marker
google.maps.event.addListener(marker, "click", function() {
infowindow.open(map, this);
});
}
// Zoom and center the map to fit the markers
var bounds = new google.maps.LatLngBounds();
for (index in markers) {
var data = markers[index];
geocoder.geocode( { 'address': data.city}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
bounds.extend(new google.maps.LatLng(results[0].geometry.location));
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
map.fitBounds(bounds);
}
问题是您在标记上添加侦听器的方式。 我想我已经修复了,希望您能看到您的标记。这是您发布的jsfiddle的更新:
http://jsfiddle.net/anilkamath87/KaSjH/1/
function addMarker(data) {
alert('bang');
geocoder.geocode( { 'address': data.city}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker( {
position: results[0].geometry.location,
map: map,
title: data.venue
});
google.maps.event.addListener(marker, "click", function() { // Bind click event to each marker should be here. else marker reference not found.
infowindow.open(map, this);
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
对于完整的工作脚本,请转到JSFiddle...。此代码将帮助您绘制标记数组并调整地图的查看边界。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.