Cluster Marker Google Maps using geoCoder

|▌冷眼眸甩不掉的悲伤 提交于 2020-01-01 19:34:06

问题


Using this data

   var data = {
  'address': [
    {
      'address': '7970 GLENTIES Ln'
    },
    {
      'address': '8022 Caminito Mallorca'
    },
    {
      'address': '2750 Wheatstone St # 26'
    },
    {
      'address': '335 49th St'
    }  
  ]
};

i manage to marker them but i was unable to cluster them. below the code that I've use.

var markerArray = [];
  function initialize() {
    geocoder = new google.maps.Geocoder();
    var center = new google.maps.LatLng(37.4419, -122.1419);

    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 3,
      center: center,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
    var address;
    var markers = [];
    for (var level in data) {
        for (var i = 0; i < data[level].length; i++) {
       //   var dataPhoto = data.photos[i];
          var dataAdd =  data[level][i];
        //  alert(dataAdd.address);
        geocoder.geocode({ 'address': dataAdd.address}, function(results){            
          var marker  = new google.maps.Marker({
              map: map, 
              position: results[0].geometry.location
          });
         markerArray[i] = marker;         
        });
        }
    }
    var markerCluster = new MarkerClusterer(map, markerArray);
  }

  google.maps.event.addDomListener(window, 'load', initialize);

How can i cluster them? it seem that the MarkerClusterer is not working or i dont know.


回答1:


Because the geocodeing function is async you need to create the marker clusterer before the markers have been created.

what you should do is create the MarkerClusterer before you start geocoding and then instead of adding to a marker array you can instead just add it to the MarkerClusterer.




回答2:


Yes, geocoding function is async. so, You can add marker in cluster later on using addMarker() method.

var markerCluster = new MarkerClusterer(map, markerArray);
for (var level in data) {
    for (var i = 0; i < data[level].length; i++) {      
      var dataAdd =  data[level][i];
      geocoder.geocode({ 'address': dataAdd.address}, function(results){            
      var marker  = new google.maps.Marker({
          map: map, 
          position: results[0].geometry.location
      });
     markerArray[i] = marker;  
     markerCluster..addMarker(marker);       
    });
    }
}    


来源:https://stackoverflow.com/questions/8317594/cluster-marker-google-maps-using-geocoder

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