【发布时间】:2015-07-15 23:25:27
【问题描述】:
我正在尝试使用地址数组在谷歌地图上绘制标记。标记正确绘制(我使用了这篇文章中的提示:Multiple markers Google Map API v3 from array of addresses and avoid OVER_QUERY_LIMIT while geocoding on pageLoad)但是当我尝试将地址数组中的信息添加到标记和信息窗口时出现此错误:“TypeError:未定义不是对象(评估'地址[x][0]')"
问题似乎是在“for”循环中,每次循环时,x 都会计算出数组的长度 4。
标记和信息窗口正在工作;当我使用字符串或使用地址 [0]、地址 [1] 等时,它们会出现,但是当我尝试执行地址 [x] 时,一切都会中断,因为地址 [4] 不存在。关于如何遍历地址数组以正确设置标记标题和信息窗口的任何指针?
注意:如果它是相关的,那么在 calcRoute() 函数中声明地址变量是有原因的。
这是代码:
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var chicago = new google.maps.LatLng(41.850033, -87.6500523);
geocoder = new google.maps.Geocoder();
var mapOptions = {
zoom:7,
center: chicago
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map);
}
function calcRoute() {
var start = document.getElementById('start').value;
var end = document.getElementById('end').value;
var request = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var addresses = [["Beaver Creek Smokehouse","4.5",["601 Main St","Martinez, CA 94553"]],["Lemongrass Bistro","4.5",["501 Main St","Martinez, CA 94553"]],["Picnicky's Sandwich Shop","4.0",["3833 Sonoma Blvd","Vallejo, CA 94590"]],["LV Vietnamese Pho and Sandwiches","4.0",["2621 Springs Rd","Vallejo, CA 94591"]]];
var infowindow = new google.maps.InfoWindow();
var marker, x;
//This is the problem area:
for (x = 0; x < addresses.length; x++) {
jQuery.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addresses[x][2]+'&sensor=false', null, function (data) {
console.log(x); // logs the length of array, 4, every time
var p = data.results[0].geometry.location;
var latlng = new google.maps.LatLng(p.lat, p.lng);
marker = new google.maps.Marker({
position: latlng,
map: map,
title: 'this works' // markers don't show when I use addresses[x][0]
});
google.maps.event.addListener(marker, 'click', (function(marker, x) {
return function () {
infowindow.setContent(addresses[x][0]);
infowindow.open(map,marker);
};
})(marker, x));
});
}
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
【问题讨论】:
-
没有意识到差异。我正在使用来自另一个 Stackoverflow 答案的代码 sn-p。我阅读了其中的差异,并已更改为使用 Javascript API。感谢您指出这一点。
标签: javascript arrays google-maps google-maps-api-3