【问题标题】:Having trouble getting coordinates from Google Maps API Javascript从 Google Maps API Javascript 获取坐标时遇到问题
【发布时间】:2016-12-23 18:53:23
【问题描述】:

我正在使用 google maps api 和路线服务来检索有关两个城市的信息。我的请求检索了 json,并且我将一些响应用于其他事情,但我无法弄清楚如何从中获取坐标。

如您所见,它们在“Closure”和“[[Scopes]]”下被列为“a”和“b” from the json response in the console,但我无法通过调用类似的方法访问它们

json.routes[0].legs[0].start_location.lat["[[Scopes]]"][0].b

我收到“无法读取未定义的属性 '0'”的错误。

我认为这与它在 [[Scopes]] 内有关,但我不知道该怎么做

编辑:要清楚我的代码看起来像这样:

    var map;
    function initMap() {

        var directionsService = new google.maps.DirectionsService;
        var directionsDisplay = new google.maps.DirectionsRenderer;
        map = new google.maps.Map(document.getElementById('map'), {
            zoom: 7,
            center: {lat: 43.16, lng: -77.61}
        });
        var geocoder = new google.maps.Geocoder();

        directionsDisplay.setMap(map);
        directionsDisplay.setOptions( { suppressMarkers: true } );

        var onChangeHandler = function() {
            directionsService.route({
                origin: document.getElementById('start').value,
                destination: document.getElementById('end').value,
            travelMode: 'DRIVING'
            }, function(response, status) {

                if (status === 'OK') {
                    getDirections(response);
                    directionsDisplay.setDirections(response);

                } else {
                    window.alert('Directions request failed due to ' + status);
                }
            });

        };
        document.getElementById('submit').addEventListener('click', onChangeHandler);

    }

function getDirections(json) {
    var time = json.routes[0].legs[0].duration.value;
    time = time/3600;
    startCityLat = json.routes[0].legs[0].start_location.lat["[[Scopes]]"][];
    startCityLon = json.routes[0].legs[0].start_location.lat["[[Scopes]]"][0].b;
    endCityLat = json.routes[0].legs[0].end_location.lat;
    endCityLon = json.routes[0].legs[0].end_location.lng;
}

</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=XXXXX&callback=initMap">
</script>

在 getDirections 函数中,时间变量可以很好地检索,但开始和结束 lat 和 lon 不是

【问题讨论】:

  • 您能否发布一个简短的示例代码,说明您是如何获得该 JSON 的?你提出什么要求?
  • @chrki 我只是在使用maps.googleapis.com/maps/api/…

标签: javascript json google-maps google-maps-api-3


【解决方案1】:

start_location 是一个 LatLng 对象。所以你可以直接使用它,或者如果你愿意,你可以调用.lat().lng() 函数。忽略将 LatLng 对象记录到控制台时可以看到的各种内容;你可以这样做

startCityLat = json.routes[0].legs[0].start_location.lat();
startCityLon = json.routes[0].legs[0].start_location.lng();

【讨论】:

  • 是的,这是有道理的!谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-15
相关资源
最近更新 更多