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)

本文介绍如何使用Ajax和Google Maps API验证地址的有效性,并提供了代码示例。主要内容包括利用AJAX传递城市名称验证城市是否存在,以及处理空格错误的方法。此外,文章还提到了通过天气预报网站接口进行地址验证的可能方法。
373

被折叠的 条评论
为什么被折叠?



