0

我正在尝试构建一个 Web 应用程序,该应用程序从服务器中提取数据并从 JSON 响应中向谷歌地图添加多个标记。这是 JSON 响应的样子:

{"key":[{"Latitude":"60.186518","Longitude":"24.950575"}...]}

我试图实现这篇文章中的代码,但我无法让它工作。

到目前为止,这是我的代码:

    function success(position) {
  var mapcanvas = document.createElement('div');
  mapcanvas.id = 'mapcontainer';
  mapcanvas.style.height = '600px';

  document.querySelector('article').appendChild(mapcanvas);
  var coords = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
  var options = {
    zoom: 15,
    center: coords,
      panControl: false,
  zoomControl: false,
  mapTypeControl: false,
  scaleControl: false,
  streetViewControl: false,
  overviewMapControl: true,

    navigationControlOptions: {
      style: google.maps.NavigationControlStyle.SMALL
    },
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  var map = new google.maps.Map(document.getElementById("mapcontainer"), options);
  var marker = new google.maps.Marker({
      position: coords,
      map: map,
      title:"You are here!"});

 function getLocations() {

    $.getJSON("http://myurl.com/jsonresponse", function (json) {

        var location;


        $.each(json.key, function (i, item) {
            addMarker(item.Latitude,item.Longitude);
        });

    });
}

function addMarker(lat,lng) {
        marker = new google.maps.Marker({
            position: new google.maps.LatLng(lat,lng),
            map: map,
        });
        markersArray.push(marker);
}

}
if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(success);
} else {
  error('Geo Location is not supported');
}
4

1 回答 1

1

请试试这个:

      function getLocations() {
            $.ajax({
              url: 'http://myurl.com/jsonresponse',
              async:false,
              success: function(data) {
                 $.each(data.key, function(index) {
                    addMarker(data[index].Latitude,data[index].Longitude);
                  });
              }
            }); 
        }

其他明智的做法是在 addMarker 函数中使用 console.log(lat,lng) 并在此处复制输出。

于 2013-03-26T10:32:27.303 回答