我似乎无法使markerLabel访问locations数组中的位置i,1。我已经移动了它,无论我放置在什么地方,它都会对所有6个markerLabel(位置[5] [1])返回45。我应该在循环中运行一个markerLabel 31,markerLabel 33,markerLabel 34等。位置[i] [0]中找到的地址全部正确显示。我已经评论了我认为应该去的次要地方,并把它留在了我认为应该的地方。我所缺少的任何见解将不胜感激。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Google Maps Multiple Markers</title>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
</head>
<body>
<div id="map" style="width: 500px; height: 400px;"></div>
<script type="text/javascript">
$(document).ready(function () {
var locations = [
['3026 East College Ave, Ruskin, Fl, USA','31'],
['517 19th Street Northwest, Ruskin, Fl, USA','33'],
['101 College Avenue East, Ruskin, Fl, USA','34'],
['3350 Laurel Ridge Ave, Ruskin, Fl, USA','37'],
['409 Laguna Mill Dr, Ruskin, Fl, USA','40'],
['2302 Lloyd Dr, Ruskin, Fl, USA','45']
];
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: new google.maps.LatLng(27.714616,-82.393298),
mapTypeId: google.maps.MapTypeId.HYBRID
});
var marker, i, markerLabel;
for (i = 0; i < locations.length; i++) {
var markerLabel = locations[i][1];
$.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+locations[i][0]+'&sensor=false', null, function (data) {
var p = data.results[0].geometry.location
//var markerLabel = locations[i][1];
marker = new google.maps.Marker({
position: new google.maps.LatLng(p.lat, p.lng),
map: map,
label: {
//text: locations[i][1];
text: markerLabel,
color: "#fff",
fontSize: "16px",
fontWeight: "bold"
} //label
}); // Marker
}); //$.getJSON
} //for (i = 0; i < locations.length; i++)
}); //$(document).ready(function ()
</script>
最佳答案
对$.getJSON
的调用是异步的。这意味着,循环将立即运行其所有迭代,并触发这些异步调用。在任何ajax调用完成之前,它将快速连续地更改i
和markerValue
的值6次,然后当这些函数最终完成并触发其回调时,它们最终将访问其值中已更改的值。范围,最终得到相同的结果。
您需要隔离单个ajax请求的范围,以使它们不都引用相同的变量。这应该足以做到这一点:
function make_request(i) {
$.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+locations[i][0]+'&sensor=false', null, function (data) {
var p = data.results[0].geometry.location
marker = new google.maps.Marker({
position: new google.maps.LatLng(p.lat, p.lng),
map: map,
label: {
text: locations[i][1],
color: "#fff",
fontSize: "16px",
fontWeight: "bold"
} //label
}); // Marker
}); //$.getJSON
}
for (i = 0; i < locations.length; i++) {
make_request(i);
} //for (i = 0; i < locations.length; i++)