第一次尝试在此处一起破解一些Javascript,以便能帮助我理解问题案例的任何资源受到赞赏。
我正在尝试从以下请求中提取经纬度并用于其他请求:
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());
});
}
}
当用户选择自动完成的位置时,Google api会发出以下请求:
https://maps.googleapis.com/maps/api/place/js/PlaceService.GetPlaceDetails
在所选位置上。我可以看到这里返回了我想要的数据:
很显然,autocomplete.result.geometry.lat
返回了一个location_search.js:18 Uncaught TypeError: Cannot read property 'geometry' of undefined
错误,因此我在这里缺少一些知识。
谢谢您的帮助。
答案 0 :(得分:0)
我最近在我的项目中实现了与您的需求非常相似的东西。这很容易,但是花了我一段时间才意识到该怎么做。
基本上,您可以简单地在自动完成对象上使用.getPlace()方法,然后从那里开始。这是我获得经度和纬度的方式:
img(src=movie.Poster)
在特定情况下,您应该将showPositions函数更改为
let locationInfo = autocomplete.getPlace().geometry.location;
let latitude = locationInfo.lat();
let longitude = locationInfo.lng();
}
这有用吗?