【发布时间】:2018-03-11 06:18:28
【问题描述】:
我似乎无法让 markerLabel 访问位置数组中的位置 i,1。我已经移动了它,无论我把它放在哪里,它都会为所有 6 个标记标签返回 45,即位置 [5] [1]。我应该有一个 markerLabel 31、markerLabel 33、markerLabel 34 等,因为它通过循环运行。在locations[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>
【问题讨论】:
-
虽然不完全相同,但链接的答案确实解决了类似的问题。它是通过闭包实现的,这是一个值得了解的概念,你是否会花很多时间在 javascript 上。
-
除了它正确输出元素 1 全部 6 次但元素 2 显示全部 6 次输出。您的链接显示它仅输出最后一个元素。这里情况不同。第一个元素是正确的。只有第二个元素是错误的。
标签: javascript