1

我一直在尝试制作一个在谷歌地图上显示多个标记的网络应用程序。我尝试使用本教程并且代码运行良好,直到我需要从服务器获取 JSON 数据,而不是使用与代码相同的 js 文件中的示例 JSON 数据。

我尝试将 ajax 响应保存到变量中,但出现此错误

TypeError: json is null
[Break On This Error]   

for (var i = 0, length = json.length; i < length; i++) {

这是我正在使用的代码。

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <style type="text/css">
      html { height: 100% }
      body { height: 100%; margin: 0; padding: 0 }
      #map-canvas { height: 100% }
    </style>
     <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
     <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
     <script src="http://code.jquery.com/jquery-migrate-1.1.1.min.js"></script>
    </script>
    <script type="text/javascript">
      function initialize() {
        var mapOptions = {
           center: new google.maps.LatLng(57.9, 14.6),
          zoom: 5,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(document.getElementById("map-canvas"),
            mapOptions);


         var json = (function () { 
            var json = null; 
                $.ajax({ 
                    'async': false, 
                    'global': false, 
                    'url': "http://myurl.com/getdata", 
                    'dataType': "json", 
                    'success': function (data) {
                     json = data; } }); 
                return json;})(); 



for (var i = 0, length = json.length; i < length; i++) {
  var data = json[i],
      latLng = new google.maps.LatLng(data.lat, data.lng); 

  // Creating a marker and putting it on the map
  var marker = new google.maps.Marker({
    position: latLng,
    map: map,
    title: data.title
  });
}

var infoWindow = new google.maps.InfoWindow();

// Attaching a click event to the current marker
google.maps.event.addListener(marker, "click", function(e) {
  infoWindow.setContent(data.description);
  infoWindow.open(map, marker);
});

// Creating a closure to retain the correct data 
//Note how I pass the current data in the loop into the closure (marker, data)
(function(marker, data) {

  // Attaching a click event to the current marker
  google.maps.event.addListener(marker, "click", function(e) {
    infoWindow.setContent(data.description);
    infoWindow.open(map, marker);
  });

})(marker, data);



      }
      google.maps.event.addDomListener(window, 'load', initialize);
    </script>
  </head>
  <body>
    <div id="map-canvas"/>
  </body>
</html>
4

0 回答 0