谷歌地图API-从方向的原点检索定位

Google maps API - retrieve latlng from origin of directions?

本文关键字:原点 点检索 定位 方向 API- 谷歌地图      更新时间:2023-09-26

我想知道如何在计算路线时从方向请求的来源检索latlng。我想用这个来画一个圆圈,围绕着路线的起点。

function calcRoute() {
start = document.getElementById("start").value; //value from start textbox
end = document.getElementById("end").value; //value from end textbox
var request = {
    origin: start,
    destination: end,
    travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(result, status) {
    //if route can be generated
    if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setDirections(result);
        //circle.setCenter();
    }else{
        //display window alert with status error
        window.alert('Directions request failed due to ' + status);
    }
});
}

用于起点和终点的文本框使用谷歌开发页面中的autocomplete方法,该方法位于返回所有类型位置的初始化函数中。

//autocomplete section
var inputStart = document.getElementById('start');
var optionsStart = {}; //Empty which will return all types
autocomplete = new google.maps.places.Autocomplete(inputStart, optionsStart);
var inputEnd = document.getElementById('end');
var optionsEnd = {}; //Empty which will return all types
autocomplete = new google.maps.places.Autocomplete(inputEnd, optionsEnd);
//--------------------------------------------------

我研究过,我是否只需要返回地址,然后使用地理编码器来检索我想要的数据,或者这可以用我现在的代码来完成。

我看过这段代码,但如果这也有帮助的话,我不知道如何实现它。

 result.routes[0].legs[0].start_location;

这是可行的。。。

result.routes[0].legs[0].start_location是LatLng对象。

因此,您可以使用它来创建标记或设置圆心。不过,我们错过了您创建圆的代码。但你可以这样做:

circle.setCenter(result.routes[0].legs[0].start_location);

如果你的圆圈还没有创建:

var circleOptions = {
    fillColor: '#FFFFFF',
    fillOpacity: 0.25,
    map: map,
    center: result.routes[0].legs[0].start_location,
    radius: 10000
};
var circle = new google.maps.Circle(circleOptions);

下面是一个完整的例子:

JSFiddle演示