首页 > 解决方案 > 未捕获的类型错误:无法读取未定义的属性“几何”

问题描述

我已经让谷歌自动完成工作,但万一用户没有选择自动完成,我试图将地址提交给谷歌并自己检索纬度和经度。我遇到的问题是,当我在不使用自动完成的情况下提交时,我得到了 Uncaught

类型错误:

无法读取未定义和未捕获类型错误的属性“几何”:无法读取未定义的属性“位置”(我的 console.logs 均未触发)。

如果我使用自动完成提交,我仍然会得到 Uncaught

TypeError:无法读取未定义的属性“几何”

即使自动完成功能确实可以获取经纬度的地址。

我的 HTML

<form method="GET" id="my-form" action="/search" onsubmit="check()">
<input class="form-control" id="getaddy" type="text" placeholder="Search..." name="term" onFocus="geo()">
<input id="latitude" type="hidden" name="latitude">
<input id="longitude" type="hidden" name="longitude">
</form>

我称之为geo()自动完成,但如果他们不使用自动完成,我会尝试使用我的 check() 函数在提交时捕获它。这是我的 JS

function check() {
let latitude = document.getElementById("latitude").value;
if (latitude) {
     console.log(latitude);
  } else {

let term = $("#getaddy").val();

$.ajax({
    url: "https://maps.googleapis.com/maps/api/geocode/json?address="+encodeURIComponent(term) +"&key=GOOGLEKEY",
    type: 'get',
    success: function(data) {
        if (data.status === 'OK') {
            // Get the lat/lng from the response
            let lat = data.results[0].geometry.location.lat;
            let lng = data.results[0].geometry.location.lng;

            console.log("pass");

        }
    },
    error: function(msg) {
        console.log("fail");
    }
});
    return true;
}
}


function geo() {

  autocomplete = new google.maps.places.Autocomplete(
    (document.getElementById('getaddy')), {
      types: ['geocode']
    });
  autocomplete.addListener('place_changed', addlatlong);
}
function addlatlong() {

var place = autocomplete.getPlace();

var latitude = place.geometry.location.lat();
var longitude = place.geometry.location.lng();

document.getElementById("latitude").value = latitude;
document.getElementById("longitude").value = longitude;
}

非常感谢您的帮助!

标签: javascriptgoogle-places-apigoogle-placestypeerror

解决方案


如果您已经拥有两个属性值latitudeand longitude,我建议您使用此代码(由 Google 提供)来获取地址(不使用 jquery ajax):

var geocoder = new google.maps.Geocoder;
var latlng = { lat: latitude, lng: longitude };

geocoder.geocode({ 'location': latlng }, function (results, status) {
    if (status === 'OK') {
        if (results[0]) {
            var address = results[0].formatted_address);
            console.log(address);
        } else {
            console.log('No results found');
        }
    } else {
        console.log('Geocoder failed due to: ' + status);
    }
});

来源:反向地理编码(地址查找)

如果他们没有提交请求,你可以尝试使用jquery捕捉searchBox失去焦点时的事件(focusout),然后调用事件places_changed获取latitudelongitude

来源:地点搜索框

来源:从提交按钮触发谷歌地图中的places_changed


推荐阅读