如何使用地址在Google地图上标记多个位置?

时间:2019-06-16 12:51:16

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

我的数据库充满了多个地址,我正尝试使用Google Maps API标记所有地址。我以前使用过此代码,但一次只能使用一个位置。

<!DOCTYPE html>
<html> 
<head> 
   <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
   <title>Google Maps Geocoding Demo 1</title> 
   <script src="http://maps.google.com/maps/api/js?sensor=false" 
           type="text/javascript"></script> 
</head> 
<body> 
   <div id="map" style="width: 400px; height: 300px;"></div> 

   <script type="text/javascript"> 

   var address = 'London, UK';

   var map = new google.maps.Map(document.getElementById('map'), { 
       mapTypeId: google.maps.MapTypeId.TERRAIN,
       zoom: 6
   });

   var geocoder = new google.maps.Geocoder();

   geocoder.geocode({
      'address': address
   }, 
   function(results, status) {
      if(status == google.maps.GeocoderStatus.OK) {
         new google.maps.Marker({
            position: results[0].geometry.location,
            map: map
         });
         map.setCenter(results[0].geometry.location);
      }
   });

   </script> 
</body> 
</html>

1 个答案:

答案 0 :(得分:0)

您可以使用PHP脚本从数据库中返回地址,然后在Javascript中循环浏览。

function getAddresses() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            a = JSON.parse(this.responseText);
            placeMarkers(a);
        }
    };
    xhttp.open("GET", "getaddresses.php", true);
    xhttp.send();
}
function placeMarkers(a) {
    var geocoder = new google.maps.Geocoder();
    for(var x=0; x<a.length; x++) {
        geocoder.geocode({
            'address': a[x]
         }, 
         function(results, status) {
            if(status == google.maps.GeocoderStatus.OK) {
               new google.maps.Marker({
                  position: results[0].geometry.location,
                  map: map
               });
               map.setCenter(results[0].geometry.location);
            }
         });
    }
}

getaddresses.php

<?php 
$query = mysqli_query($link, "SELECT Address FROM AddressTable");
$addresses = [];
while($queryinfo = mysqli_fetch_array($query)) {
    array_push($addresses, $queryinfo['Address']);
}
$addresses = json_encode($addresses);
print $addresses;
?>

然后只需调用getAddresses()

刚刚在多个地址上进行了测试,在10个查询后我遇到了Over_Limit错误。