我尝试从JSON文件创建路径,但我无法显示路径。控制台中没有错误或指示为什么会这样。除了getJSON循环之外,此代码直接来自Google Example。当我尝试将新坐标对推入数组时出现问题。
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Simple Polylines</title>
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script>
function initialize() {
var mapOptions = {
zoom: 3,
center: new google.maps.LatLng(0, -180),
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var routeCoordinates = [];
$.getJSON('Tour_Down_Under_Stage_One.json', function(data) {
for (var i in data.points) {
coordinates = new google.maps.LatLng(data.points[i].latitude, data.points[i].longitude)
routeCoordinates.push(coordinates);
}
});
var route = new google.maps.Polyline({
path: routeCoordinates,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
route.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
这就是文件的样子。我知道它正确解析,因为我可以控制.log数据就好了。这是构建阵列的一部分。
{
"points": [
{
"distance": 0.0,
"latitude": -34.964927695699998,
"longitude": 138.647018457,
"elevation": 169.94999999999999
},
{
"distance": 0.0,
"latitude": -34.964927695699998,
"longitude": 138.647018457,
"elevation": 169.94999999999999
},
{
"distance": 8.1500000000000004,
"latitude": -34.964965833400001,
"longitude": 138.647094732,
"elevation": 170.0
},
{
"distance": 17.93,
"latitude": -34.965011598499999,
"longitude": 138.64718626300001,
"elevation": 170.06999999999999
},
{
"distance": 27.079999999999998,
"latitude": -34.965064991299997,
"longitude": 138.64726253800001,
"elevation": 170.36000000000001
},
{
"distance": 52.659999999999997,
"latitude": -34.965213769999998,
"longitude": 138.64747619299999,
"elevation": 171.03999999999999
},
{
"distance": 63.43,
"latitude": -34.965274790300001,
"longitude": 138.64756772300001,
"elevation": 172.0
},
{
"distance": 73.459999999999994,
"latitude": -34.965339666200002,
"longitude": 138.647644082,
"elevation": 172.97
},
{
"distance": 84.780000000000001,
"latitude": -34.965408314000001,
"longitude": 138.64773561199999,
"elevation": 173.96000000000001
},
// LOTS MORE OF THESE //
],
"totalDistance": 138442.46999999991,
"routeName": "Tour_Down_Under_Stage_One"
}
答案 0 :(得分:1)
$.getJSON()
是一个异步函数。函数返回后,它获取的JSON数据不可用,您的代码尝试使用它。相反,您需要将此代码移动到 {@ 1}}回调中,或者在此回调调用的函数中移动。
此外,您不应使用$.getJSON()
循环来遍历数组。要么使用旧式数字for..in
循环,要么使用for
等。
因此,代码的固定(但未经测试)版本可能如下所示:
.forEach()