placing multiple markers on google map from array

荒凉一梦 提交于 2019-12-21 05:11:11

问题


I'm trying to place multiple markers on a map that are provided from an array. Right now only my initial point loads (NYC).

var geocoder;
var map;
var markersArray = [];

//plot initial point using geocode instead of coordinates (works just fine)
  function initialize() {
    geocoder = new google.maps.Geocoder();
     latlang = geocoder.geocode( { 'address': 'New York City'}, function(results, status) { //use latlang to enter city instead of coordinates 
            if (status == google.maps.GeocoderStatus.OK) {
                map.setCenter(results[0].geometry.location);
                marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location
                });
            markersArray.push(marker);
            }
            else{
            alert("Geocode was not successful for the following reason: " + status);
            }
        });
    var myOptions = {
        center: latlang, zoom: 5, mapTypeId: google.maps.MapTypeId.SATELLITE,
        navigationControlOptions: {
            style: google.maps.NavigationControlStyle.SMALL
        }
    };
     map = new google.maps.Map(document.getElementById("map_canvas"),
        myOptions);

  }

///////////////////////////////////////////////////////////
//Everything below this line is for attempting to plot the markers

  var locationsArray = ['Pittsburgh','Chicago', 'Atlanta'];

  function plotMarkers(){
for(var i = 0; i < locationsArray.length; i++){
  codeAddresses(locationsArray[i]);
}
  }

  function codeAddresses(address){
    geocoder.geocode( { 'address': address}, function(results, status) { 
            if (status == google.maps.GeocoderStatus.OK) {
                map.setCenter(results[0].geometry.location);
                marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location
                });
            //markersArray.push(marker); 
            }
            else{
            alert("Geocode was not successful for the following reason: " + status);
            }
  });
  }

回答1:


You're not actually calling plotMarkers anywhere in the snippet above! When I added into the end of initialize (after map is defined) it works great! http://jsfiddle.net/T5aKE/

       ...
         map = new google.maps.Map...
         plotMarkers();
       ...


来源:https://stackoverflow.com/questions/10688509/placing-multiple-markers-on-google-map-from-array

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