Подтвердить что ты не робот

Несколько маркеров Google Map API v3 из массива адресов и избегайте OVER_QUERY_LIMIT во время геокодирования на страницеLoad

Мне нужно реализовать функцию множественных маркеров из массива адресов. Строка адресов извлекается из базы данных.

Мой массив адресов выглядит так:

    var address = <?php echo $add_js ?>;

Я прошел так много примеров в Интернете и даже на этом форуме, но в большинстве примеров широта и долгота уже доступны в этих базах данных. Есть ли способ, чтобы я использовал этот массив адресов и помещал несколько маркеров на карту google. или какой-либо пример, где объясняется этот тип концепции?!

Я практиковал этот пример из JSFIDDLE, но я не получаю выход.

       <script>
   var geocoder;
       var map;
       var markersArray = [];

   function initialize() 
    {
        geocoder = new google.maps.Geocoder();

    latlang = geocoder.geocode( { 

           'address': 'New Delhi, India'},                                             

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

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

               var locationsArray = new Array(
               "New Delhi, India", "Gurgaon,Haryana,  India", "Mumbai, India", 
               "Noida Sector-63,India","Banglore, Karnataka,India");

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

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

        </script>
4b9b3361

Ответ 1

Ответьте, чтобы добавить несколько маркеров.

ОБНОВЛЕНИЕ (НЕКОТОРЫЕ АДРЕСА ГЕОКОДА)

Здесь приведен пример рабочего геокодирования с несколькими адресами.

 <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
 </script> 
 <script type="text/javascript">
  var delay = 100;
  var infowindow = new google.maps.InfoWindow();
  var latlng = new google.maps.LatLng(21.0000, 78.0000);
  var mapOptions = {
    zoom: 5,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  var geocoder = new google.maps.Geocoder(); 
  var map = new google.maps.Map(document.getElementById("map"), mapOptions);
  var bounds = new google.maps.LatLngBounds();

  function geocodeAddress(address, next) {
    geocoder.geocode({address:address}, function (results,status)
      { 
         if (status == google.maps.GeocoderStatus.OK) {
          var p = results[0].geometry.location;
          var lat=p.lat();
          var lng=p.lng();
          createMarker(address,lat,lng);
        }
        else {
           if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
            nextAddress--;
            delay++;
          } else {
                        }   
        }
        next();
      }
    );
  }
 function createMarker(add,lat,lng) {
   var contentString = add;
   var marker = new google.maps.Marker({
     position: new google.maps.LatLng(lat,lng),
     map: map,
           });

  google.maps.event.addListener(marker, 'click', function() {
     infowindow.setContent(contentString); 
     infowindow.open(map,marker);
   });

   bounds.extend(marker.position);

 }
  var locations = [
           'New Delhi, India',
           'Mumbai, India',
           'Bangaluru, Karnataka, India',
           'Hyderabad, Ahemdabad, India',
           'Gurgaon, Haryana, India',
           'Cannaught Place, New Delhi, India',
           'Bandra, Mumbai, India',
           'Nainital, Uttranchal, India',
           'Guwahati, India',
           'West Bengal, India',
           'Jammu, India',
           'Kanyakumari, India',
           'Kerala, India',
           'Himachal Pradesh, India',
           'Shillong, India',
           'Chandigarh, India',
           'Dwarka, New Delhi, India',
           'Pune, India',
           'Indore, India',
           'Orissa, India',
           'Shimla, India',
           'Gujarat, India'
  ];
  var nextAddress = 0;
  function theNext() {
    if (nextAddress < locations.length) {
      setTimeout('geocodeAddress("'+locations[nextAddress]+'",theNext)', delay);
      nextAddress++;
    } else {
      map.fitBounds(bounds);
    }
  }
  theNext();

</script>

Как можно решить эту проблему с помощью функции setTimeout().

Тем не менее мы не должны геокодировать известные местоположения каждый раз, когда вы загружаете свою страницу, как сказано в @geocodezip

Другие альтернативы из них очень хорошо объясняются в следующих ссылках:

Как избежать ограничения геокодирования GoogleMap!

Учебное пособие по нескольким адресам в геокодировании Майк Уильямс

Пример от разработчиков Google

Ответ 2

Независимо от вашей ситуации, это рабочая демонстрация, которая создает маркеры на карте на основе массива адресов.

http://jsfiddle.net/P2QhE/

Код JavaScript, встроенный также:

$(document).ready(function () {
    var map;
    var elevator;
    var myOptions = {
        zoom: 1,
        center: new google.maps.LatLng(0, 0),
        mapTypeId: 'terrain'
    };
    map = new google.maps.Map($('#map_canvas')[0], myOptions);

    var addresses = ['Norway', 'Africa', 'Asia','North America','South America'];

    for (var x = 0; x < addresses.length; x++) {
        $.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addresses[x]+'&sensor=false', null, function (data) {
            var p = data.results[0].geometry.location
            var latlng = new google.maps.LatLng(p.lat, p.lng);
            new google.maps.Marker({
                position: latlng,
                map: map
            });

        });
    }

}); 

Ответ 3

Вот мое решение:

зависимости: Gmaps.js, jQuery

var Maps = function($) {
   var lost_addresses = [],
       geocode_count  = 0;

   var addMarker = function() { console.log('Marker Added!') };

   return {
     getGecodeFor: function(addresses) {
        var latlng;
        lost_addresses = [];
        for(i=0;i<addresses.length;i++) {
          GMaps.geocode({
            address: addresses[i],
            callback: function(response, status) {
              if(status == google.maps.GeocoderStatus.OK) {
                addMarker();
              } else if(status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
                lost_addresses.push(addresses[i]);
              }

               geocode_count++;
               // notify listeners when the geocode is done
               if(geocode_count == addresses.length) {
                 $.event.trigger({ type: 'done:geocoder' });
               }
            }
          });
        }
     },
     processLostAddresses: function() {
       if(lost_addresses.length > 0) {
         this.getGeocodeFor(lost_addresses);
       }
     }
   };
}(jQuery);

Maps.getGeocodeFor(address);

// listen to done:geocode event and process the lost addresses after 1.5s
$(document).on('done:geocode', function() {
  setTimeout(function() {
    Maps.processLostAddresses();
  }, 1500);
});