通过谷歌API验证地址是否存在 How Google’s Geocoding solves Address Validation

ajax.php 代码:

$address = $_GET['address'];
$xml     = file_get_contents('https://maps-api-ssl.google.com/maps/api/geocode/xml?address='.urlencode($address).'&sensor=false');
$arr     = xml2array($xml);
$output  = $arr['GeocodeResponse']['status'];

主要是利用了谷歌接口:https://maps-api-ssl.google.com/maps/api/geocode/xml?address=Frankfurstein+ring+105a,M%C3%BCnchen,de, 80000,&sensor=false&client=gme-kickzag&signature=VF930KLrbu98sKKLqIjn4adIoTs=  (from http://blog.mgm-tp.com/2011/08/address-validation-with-geocoding/

1. 代码虽短,但是有想象力,比如可以制作一个表单,提交之后验证地址。亦或者通过ajax传递一个城市的名字(当然,中国的城市必须用全拼,例如 beijing 或者 beijing shi)来验证这个城市是否有效:

$(document).on('submit', 'form', function () 
{
    $.ajaxSetup({async:false}); 
    
    var $output = false;
    var $city   = encodeURIComponent($.trim($('#inputAim_city').val()));
    
    $.post('ajax.php','address='+$city,function(data)
    { 
        if(data!='OK'){ if(confirm('不能找到地址'+$city+', 你想继续更新吗?'))$output = true; }
        else $output = true;
    });
    
    return $output;
});

2. 防止空格错误,php传递参数是一定要使用 urlencode函数,否则很容易出错

3. 有人说可以通过天气预报网站的接口进行判断,方法类似,就看谁的数据库更强大了。

$city = 'test';

$data =  file_get_contents('http://www.weather-forecast.com/locations/ac_location_name?query='.$city);

if (strlen($data) > 6) {
    echo ucfirst($city)." is valid!";
} else {
    echo ucfirst($city)." is not valid!";
}

(from: http://stackoverflow.com/a/25223140)

原创:http://justcode.ikeepstudying.com/2015/05/%E9%80%9A%E8%BF%87%E8%B0%B7%E6%AD%8Capi%E9%AA%8C%E8%AF%81%E5%9C%B0%E5%9D%80%E6%98%AF%E5%90%A6%E5%AD%98%E5%9C%A8-how-googles-geocoding-solves-address-validation/