gpt4 book ai didi

google-maps - 谷歌地图 API : how to check if an address or location is valid?

转载 作者:行者123 更新时间:2023-12-02 18:10:00 25 4
gpt4 key购买 nike

这是我的问题:我有一个网页,我正在尝试使用自动完成,就像这样,非常非常基本:

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

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

五角大楼,北扶轮路,阿灵顿,弗吉尼亚州,大学

等等。那么,在服务器端,有没有办法验证这个地址是否正确,即询问谷歌?

最佳答案

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

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

// show an error if it's not
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;
}

关于google-maps - 谷歌地图 API : how to check if an address or location is valid?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34339521/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com