这真让我疯狂。为什么我的数组失去了将其移入for循环的范围?请查看此代码,var'marker'在此脚本开头附近丢失范围。欢迎任何想法。
<!DOCTYPE html>
<html>
<head>
<script
src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDY0kkJiTPVd2U7aTOAwhc9ySH6oHxOIYM&sensor=false">
</script>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
//var cell={};
var cellcenter = new Array();
var lat = ''; var lng='';
$(document).ready(function(){
i=0;
$.getJSON('http://www.perivision.net/testing/containment/containment.php', function(data) {
var marker = new Array();
marker[0]=9;
$('#output').html('this works '+marker[0]);
for (index in data) {
i++;
$('#output').html(' this does not '+marker[0]);
for (element in data[index]) {
//console.log(element);
//console.log(data[index][element]);
if (element=="attribute8"){
lat=data[index][element];
}
if (element=="attribute9"){
//cell[i]=data[index][element];
lng=data[index][element];
cellcenter[i]=new google.maps.LatLng(lat,lng);
var myLatlng = new google.maps.LatLng(51.508742,-0.120850);
var mapOptions = {
zoom: 4,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
}
var map= new google.maps.Map(document.getElementById("googleMap"),mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
title:"Hello World!"
});
marker[i] = new google.maps.Marker({
position: cellcenter[i],
title:"Hello World!"+i
});
// To add the marker to the map, call setMap();
marker.setMap(map);
//marker[0].setMap(map);
marker[i].setMap(map);
//$('#output').html('re '+marker[0]);
//console.log('ping '+i+' '+cellcenter[i]);
}
}
}
});
});
function donothing(){
}
</script>
</head>
<body>
<div id="googleMap" style="width:500px;height:380px;"></div>
<button id="requestDataBtn">Get Data</button><br />
<div id='output'></div>
</body>
</html>
答案 0 :(得分:0)
var marker = new google.maps.Marker
这是你的问题。您为其他对象指定了相同的名称marker
。现在,Javascript解释器扫描整个JS代码并在执行之前查找任何var
定义。这就是为什么尽管你已经定义了marker
mch,但仍然会重置。