我是第一次尝试在这里整合一些Javascript,所以我们非常感谢任何能帮助我理解问题的资源。
我正在尝试从以下请求中提取lat和long,以便在另一个请求中使用:
var placeSearch, autocomplete;
var x = document.getElementById("location");
function initAutocomplete() {
// Create the autocomplete object, restricting the search predictions to
// geographical location types.
autocomplete = new google.maps.places.Autocomplete(
document.getElementById('autocomplete'), { types: ['geocode'] });
// Avoid paying for data that you don't need by restricting the set of
// place fields that are returned to just the address components.
autocomplete.setFields(['geometry']);
}
function showPosition() {
x.innerHTML = "Latitude: " + autocomplete.result.geometry.lat +
"<br>Longitude: " + autocomplete.result.geometry.lng;
}
/*
"result" : {
"geometry" : {
"location" : {
"lat" : 51.46588129999999,
"lng" : -0.1413263
}
}
*/
// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
function geolocate() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var geolocation = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var circle = new google.maps.Circle(
{ center: geolocation, radius: position.coords.accuracy });
autocomplete.setBounds(circle.getBounds());
});
}
}
显然,autocomplete.result.geometry.lat
返回一个location_search.js:18 uncapted typeerror:无法读取undefined
错误的属性“geometry”,因此这里我缺少了一些知识。
谢谢你的帮助。
我最近在我的项目中实现了一些与您的需求非常相似的东西。 这很容易,但我花了一段时间才意识到该怎么做。
基本上,您可以简单地在Autocomplete对象上使用。getPlace()方法,然后从那里开始。 下面是我得到经纬度的方法:
let locationInfo = autocomplete.getPlace().geometry.location;
let latitude = locationInfo.lat();
let longitude = locationInfo.lng();
在您的特定情况下,应该将showPositions函数更改为
function showPosition() {
x.innerHTML = "Latitude: " + autocomplete.getPlace().geometry.location.lat +
"<br>Longitude: " + autocomplete.getPlace().geometry.location.lng;
}
这个有用吗?