【问题标题】:Multiple markers Google Map API v3 from array of addresses and avoid OVER_QUERY_LIMIT while geocoding on pageLoad来自地址数组的多个标记 Google Map API v3 并在 pageLoad 上进行地理编码时避免 OVER_QUERY_LIMIT
【发布时间】:2013-11-07 12:51:28
【问题描述】:

我必须从地址数组中实现多个标记功能。正在从数据库中获取地址字符串。

我的地址数组如下所示

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

我在互联网上甚至在这个论坛上浏览了很多示例,但在大多数示例中,纬度和经度已经在这些数据库中可用。有什么办法可以让我使用该地址数组并在谷歌地图上放置多个标记。 或解释此类概念的任何示例?!

我已经从 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>

【问题讨论】:

  • 如果您的数组中有超过 10 个地址,您将遇到地理编码器的配额和查询限制。您不想在页面加载时对地址进行地理编码,当然也不希望知道地址(除非您构建自己的地理编码器)。
  • @geocodezip 那么我应该遵循哪些步骤才能使其可行?我当然有超过 10 个地址的数据库。
  • 你应该离线地理编码这些地址(如果你使用谷歌的地理编码器,你只能暂时“缓存”它们,所以你需要添加一个机制来定期重新地理编码地址),然后使用坐标来在页面加载时放置标记。
  • @geocodezip 先生,您能给我一些关于这个概念的教程链接吗?
  • 嘿,agnes 如果您有超过 10 个地址会发生什么,您找到解决方案了吗?

标签: javascript arrays google-maps google-maps-api-3


【解决方案1】:

无论您的情况如何,这里都有一个工作演示,它根据地址数组在地图上创建标记。

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

        });
    }

}); 

【讨论】:

  • 对数组使用 jQuery $.each() 调用。它比“for”循环容易得多。 $.each(addresses, function(){ /*你的代码在这里*/);
  • 我需要放大。我该怎么做?
  • 在 myOptions 中增加 Zoom 的值。
  • 这并不能避免 OVER_QUERY_LIMIT 错误。
  • 我明白了,每次都会发起一个新的 http 请求进行地理编码。这不能用一个请求 api 完成吗?
【解决方案2】:

回答添加多个标记。

更新(地理编码多个地址)

这是具有多个地址的工作示例地理编码。

 <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 所说的那样每次加载页面时对已知位置进行地理编码

以下链接很好地解释了这些替代方案:

How To Avoid GoogleMap Geocode Limit!

Geocode Multiple Addresses Tutorial By Mike Williams

Example by Google Developers

【讨论】:

  • 嗨@analyticalpicasso,我使用了您的代码,稍作修改,并且运行良好。 问题:当我在同一页面中使用 4 个过滤器函数(例如调用 API 以根据过滤器获取新位置)时,地图没有重新加载。 未删除已映射的位置,未更新新位置您能帮我解决这个问题吗?谢谢。
【解决方案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);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-08
    • 1970-01-01
    • 2016-07-20
    • 1970-01-01
    • 2014-05-14
    • 2013-10-05
    相关资源
    最近更新 更多