当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Google maps API - retrieve latlng from origin of directions?

问题描述:

Im wondering on how to retrieve the latlng from the origin of a directions request when the route has been calculated.

I want to use this to draw a circle around the origin of the route thats been made.

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);

}

});

}

The textboxes that are used for the origin and destination use the autocomplete method from the google dev page which is inside my initialise function that returns all types of locations.

//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);

//--------------------------------------------------

ive researched about, would I need to just return addresses then use a geocoder to retreive the data I want or can this be done with the way my code is now.

I have seen this piece of code around, but no idea how to implement it if this helps too.

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

网友答案:

That would work yes...

result.routes[0].legs[0].start_location is a LatLng object.

So you can use that to create a marker or set your circle center point. We miss the code where you create the circle though. But you could do something like that:

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

and if your circle is not yet created:

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);

Below is a complete example:

JSFiddle demo

分享给朋友:
您可能感兴趣的文章:
随机阅读: