Google Maps API:如何检查地址或位置是否有效?

时间:2015-12-17 16:24:22

标签: google-maps

这是我的问题:我有一个网页,我尝试使用autocomplete,非常非常基本:

<script type="text/javascript"
        src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<script type="text/javascript">
    $(document).ready(function () {
        new google.maps.places.Autocomplete(
            document.getElementById('testtest'), {}
        );
</script>

当用户发布表单在服务器端时,我会得到一个文本值,如

&#34; Pentagone, North Rotary Road, Arlington, Virginie, États-Unis&#34;

等等。那么,在服务器端,有没有办法验证这个地址是好的,即问google?

1 个答案:

答案 0 :(得分:11)

我不知道为什么它必须在服务器端。您应该在进入谷歌后立即与Google合作。不要让他们提交表单,并且必须重新做一遍,因为你想在服务器端进行验证。

<强> HTML

<input type="text" id="address" onchange="doGeocode()" />

<!-- require Google Maps API -->
<script src="//maps.googleapis.com/maps/api/js"></script>

<强> JS

function doGeocode() {
  var addr = document.getElementById("address");
  // Get geocoder instance
  var geocoder = new google.maps.Geocoder();

  // Geocode the address
  geocoder.geocode({
    'address': addr.value
  }, function(results, status) {
    if (status === google.maps.GeocoderStatus.OK && results.length > 0) {

      // set it to the correct, formatted address if it's valid
      addr.value = results[0].formatted_address;;

      // show an error if it's not
    } else alert("Invalid address");
  });
};

但是,如果您想使用PHP,可以试试这个......

function geocode($address){
    $return = array();
    $address = urlencode($address);
    $key = "put your key here,,,";
    $url = "https://maps.google.com/maps/api/geocode/json?key=$key&address={$address}";
    $resp_json = file_get_contents($url);
    $resp = json_decode($resp_json, true);
    if($resp['status']!=='OK') return false;
    foreach($resp['results'] as $res){
        $loc = array(
            "zipcode"=>null,
            "formatted"=>null
        );
        foreach($res['address_components'] as $comp){
            if(in_array("postal_code", $comp['types'])) 
                $loc['zipcode'] = $comp['short_name'];
        }
        $loc['formatted'] = $res['formatted_address'];
        $loc['lng'] = $res['geometry']['location']['lng'];
        $loc['lat'] = $res['geometry']['location']['lat'];
        $return[] = $loc;
    }
    return $return;
}