简体   繁体   English

从JSON向Google地图添加多个标记

[英]Add multiple markers to google maps from json

I am trying to build a web app that pulls data from server and adds multiple markers to the google map from the JSON response. 我正在尝试构建一个Web应用程序,该应用程序从服务器中提取数据,并从JSON响应中向Google地图添加多个标记。 This is how the JSON response looks like: JSON响应如下所示:

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

I tried to implement the code from this post but I can't get it to work. 我试图实现从代码这个职位 ,但我不能得到它的工作。

This is my code so far: 到目前为止,这是我的代码:

    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');
}

Please try this: 请尝试以下方法:

  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); }); } }); } 

Other wise use console.log(lat,lng) in addMarker function and copy the output here. 否则,请在addMarker函数中使用console.log(lat,lng)并在此处复制输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM