我正在使用谷歌地图v3。我用json文件中的信息创建了一些标记。 我正试图在我的地图上放一些routelines,但这不起作用,我不知道为什么不这样做。
这是我的jQuery代码:
var positions = [];
var map;
$(function () {
map = initializeMap();
loadMarkers();
var flightPath = new google.maps.Polyline({
path: positions,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2
});
flightPath.setMap(map);
});
function initializeMap() {
var myOptions = {
center: new google.maps.LatLng(41.376809, -37.441406),
zoom: 3,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
return map;
};
function loadMarkers() {
var latlng;
var marker;
var image = 'img/praline.png';
$.getJSON('json/markers.json', function (data) {
$(data).each(function (index, value) {
latlng = new google.maps.LatLng(value.x, value.y);
marker = new google.maps.Marker({
position: latlng,
map: map,
title: value.title,
icon: image
});
positions[value.id - 1] = latlng;
});
});
}
这是我的json文件:
[
{
"class":"marker",
"id":1,
"x":"47.175303",
"y":"7.064539",
"title":"Camille Bloch",
"date":"21/10/2010",
"details":"<h1>Camille Bloch</h1><h4>Courtelary, CH</h4><img src='img/camille_bloch.gif' alt='Camille Bloch' width='100px'>"
},
{
"class":"marker",
"id":2,
"x":"51.903421",
"y":"4.483248",
"title":"Haven Rotterdam",
"date":"22/10/2010",
"details":"<h1>Haven Rotterdam</h1><h4>Rotterdam, NL</h4><img src='img/camille_bloch.gif' alt='Camille Bloch' width='100px'>"
}
]
提前致谢。
答案 0 :(得分:1)
由于AJAX是异步的,您需要将折线放在getJSON回调中(在实际创建LatLng之后),如下所示,或者某些变体。否则,代码只是将空位置数组设置为折线。
$.getJSON('json/markers.json', function(data) {
function(data) {
$(data).each(function(index, value) {
alert(value.x);
latlng = new google.maps.LatLng(value.x, value.y);
marker = new google.maps.Marker({
position: latlng,
map: map,
title: value.title,
icon: image
});
positions[value.id - 1] = latlng;
});
var flightPath = new google.maps.Polyline({
path: positions,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2
});
flightPath.setMap(map);
});
}