如何访问Google Maps API响应数据

问题描述 投票:1回答:1

第一次尝试在此处一起破解一些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。我可以看到这里返回了我想要的数据:enter image description here

显然autocomplete.result.geometry.lat返回一个location_search.js:18 Uncaught TypeError: Cannot read property 'geometry' of undefined错误,所以我在这里缺少一些知识。

谢谢您的帮助。

javascript google-api google-places-api google-maps-api-2
1个回答
0
投票

最近,我在项目中实现了与您的需求非常相似的功能。这很容易,但是花了我一段时间才知道如何去做。基本上,您可以简单地在Autocomplete对象上使用.getPlace()方法,然后从那里开始。这是我获得经纬度的方法:

let locationInfo = autocomplete.getPlace("geometry").geometry.location; let latitude = locationInfo.lat(); let longitude = locationInfo.lng();

希望这有帮助吗?!

© www.soinside.com 2019 - 2024. All rights reserved.