Not able to set multiple markers on the Google maps using Google map javascript api v3

只谈情不闲聊 提交于 2019-12-11 07:22:10

问题


i want to place multiple markers on the map but I'm getting a map with no markers set.

<script type="text/javascript">

  var map;
  var i;

  window.onload=function()
  {
    var mapOptions = {
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      center: new google.maps.LatLng(59.32522, 18.07002)
    };

    map = new google.maps.Map(document.getElementById("map"),mapOptions);
    var bounds = new google.maps.LatLngBounds();
         var places =[];
         places.push(google.maps.LatLng(40.756,-73.986));
         places.push(google.maps.LatLng(59.32522, 18.07002));
         places.push(google.maps.LatLng(37.775,-122.419));
         places.push(google.maps.LatLng(47.620,-122.347));
         places.push(google.maps.LatLng(-22.933,-43.184));
         for(i=0; i<places.length;i++)
      {
          var marker= new google.maps.Marker({position:places[i],map: map,title:'place Number'+i});

        bounds.extend(places[i]);

      }
      map.fitBounds(bounds);
  }
</script>

回答1:


You need to change all your lines that look like this:

     places.push(google.maps.LatLng(40.756,-73.986));

To look like this:

     places.push(new google.maps.LatLng(40.756,-73.986));

Here's your code above with these modifications. It's working for me. Try it:

<script type="text/javascript">

  var map;
  var i;

  window.onload=function()
  {
    var mapOptions = {
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      center: new google.maps.LatLng(59.32522, 18.07002)
    };

    map = new google.maps.Map(document.getElementById("map"),mapOptions);
    var bounds = new google.maps.LatLngBounds();
         var places =[];
         places.push(new google.maps.LatLng(40.756,-73.986));
         places.push(new google.maps.LatLng(59.32522, 18.07002));
         places.push(new google.maps.LatLng(37.775,-122.419));
         places.push(new google.maps.LatLng(47.620,-122.347));
         places.push(new google.maps.LatLng(-22.933,-43.184));
         for(i=0; i<places.length;i++)
      {
          var marker= new google.maps.Marker({position:places[i],map: map,title:'place Number'+i});

        bounds.extend(places[i]);

      }
      map.fitBounds(bounds);
  }
</script>



回答2:


You can write a javascript function and call after populate your results. Also you can use json push data from serverside to javascript

function showMap(locations){  
    //map code here
}


来源:https://stackoverflow.com/questions/6218616/not-able-to-set-multiple-markers-on-the-google-maps-using-google-map-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!