2012-07-08 82 views
1

我正在使用谷歌地圖v3。我創建了一些標記,並從json文件中獲取信息。 我試圖在地圖上放一些路線,但這不起作用,我不知道爲什麼不。谷歌地圖api v3未顯示折線

這裏是我的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'>" 
    } 
] 

在此先感謝。

回答

1

由於AJAX是異步的,因此您需要將multiline放入該getJSON回調(在LatLngs實際創建之後),如下所示,或者一些變體。否則,代碼只是將空位置數組設置爲多段線。

$.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); 

    });​ 
} 
+0

謝謝!這工作:) – Sllix 2012-07-08 00:24:20