javascript - 未捕获的类型错误:无法读取未定义的属性“几何”
问题描述
我已经让谷歌自动完成工作,但万一用户没有选择自动完成,我试图将地址提交给谷歌并自己检索纬度和经度。我遇到的问题是,当我在不使用自动完成的情况下提交时,我得到了 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;
}
非常感谢您的帮助!
解决方案
如果您已经拥有两个属性值latitude
and 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
获取latitude
和longitude
。
来源:地点搜索框
推荐阅读
- ruby - 如何运行这个需要参数的 ruby 文件?
- google-classroom - 如何为 Google 课堂课程设置正确的时区
- javascript - 在 MVC 页面中为谷歌地图 API 设置 JavaScript 代码时出现错误
- html - 使用 CSS 选择器有速度差异吗?
- javascript - 当我修改 DOM 时,Karma/Jasmine 测试抛出错误
- python - 重新启动 celeryd 服务时出现 Winrm 错误
- javascript - 无法使用 twitter api 验证身份验证错误?
- sql - 在sql server中的特定情况下除以零
- ruby-on-rails - 如何在rails中连接fixnum和字符串?
- docker - Grafana 使用 docker-compose.yml 和 Dockerfile 从源代码构建,路径设置错误,找不到 go 命令