谷歌地图API:如何检查地址或位置是否有效? [英] Google maps API: how to check if an address or location is valid?

查看:367
本文介绍了谷歌地图API:如何检查地址或位置是否有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我的问题:我有一个网页,我尝试使用 autocomplete ,就像那样,非常非常基本:

Here's my problem: I have a web page where I'm trying to use autocomplete, like that, very very basic:

<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>

当用户发布表单时,服务器上的我会得到一个像

When the user posts the form, on the server side, I will get a text value like

Pentagone,North Rotary Road,Arlington,Virginie,États-Unis code>

等等。所以,在服务器端,有没有一种方法可以验证这个地址是否正确请问谷歌?

and so. So, on the server side, is there a way to validate that this address is good ie ask google?

推荐答案

我不知道为什么它必须在服务器端。不要让他们提交表单,而必须重新做,因为你想在服务器端进行验证。

I don't know why it has to be on the server side. You should be doing that with Google as soon as they enter it. Don't make them submit the form and have to do it all over again because you want to do validation on the server side.

HTML

HTML

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

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

JS

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,你可以试试这个...

However, if you want to use PHP you can try this...

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

这篇关于谷歌地图API:如何检查地址或位置是否有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆