Google maps 使用谷歌地图进行地址验证-检查地址
我允许用户使用谷歌地图在帖子中添加地址 如果用户未为地图输入任何内容或输入奇数特殊字符(#$!@#),则会导致网站崩溃,并出现以下错误:Google maps 使用谷歌地图进行地址验证-检查地址,google-maps,validation,google-maps-api-3,error-handling,maps,Google Maps,Validation,Google Maps Api 3,Error Handling,Maps,我允许用户使用谷歌地图在帖子中添加地址 如果用户未为地图输入任何内容或输入奇数特殊字符(#$!@#),则会导致网站崩溃,并出现以下错误: var lat = data.results[0].geometry.location.lat; ^ TypeError: Cannot read property 'results' of undefined 我正在试图找到一种在提交表单时检查此错误的方法。到目前为止,我一点运气都没有。是否可以检查此错误 我见过这样的代
var lat = data.results[0].geometry.location.lat;
^
TypeError: Cannot read property 'results' of undefined
我正在试图找到一种在提交表单时检查此错误的方法。到目前为止,我一点运气都没有。是否可以检查此错误
我见过这样的代码,但都是未定义的,我不确定在这种情况下如何定义它,坦率地说,我不确定下面的代码是如何运行的
if (status == google.maps.GeocoderStatus.OK) {
var lat = results[0].geometry.location.lat();
var lon = results[0].geometry.location.lng();
searchStores(lat, lon);
} else {
$addressErrorP.removeClass('hide');
}
谢谢你的帮助 解决了这个问题:简单又完美 第一步:确保这在你的页面上
<script type="text/javascript" src="https://maps.google.com/maps/api/js?sensor=false"></script>
$("#checkingAddress").click(checkGeocode);
function checkGeocode(){
var addr = document.getElementById("location");
// 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) {
alert('looks good')
// 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");
});
};