拖动路线时是否可以获取LatLng?
例如,在标记中我们可以通过
获得LatLng
google.maps.event.addListener(marker, 'click', function (event) {
var latLng = event.latLng;
});
是否可以这样做?
directionDisplay.addListener('directions_changed', function (event) {
addWaypoint(event.latLng);
});
答案 0 :(得分:1)
假设您的地图与Google上的here一样,只有少数例外:
function initMap(){
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: {lat: -24.345, lng: 134.46} // Australia.
});
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer({
draggable: true,
map: map,
panel: document.getElementById('right-panel')
});
directionsDisplay.addListener('directions_changed', function() {
computeTotalDistance(directionsDisplay.getDirections());
});
displayRoute('Perth, WA', 'Sydney, NSW', directionsService, directionsDisplay);
}
function displayRoute(origin, destination, service, display){
service.route({
origin: origin,
destination: destination,
waypoints: [{location: 'Cocklebiddy, WA'}, {location: 'Broken Hill, NSW'}],
travelMode: google.maps.TravelMode.DRIVING,
avoidTolls: true
}, function(response, status){
if(status === google.maps.DirectionsStatus.OK) {
display.setDirections(response);
}
else{
alert('Could not display directions due to: ' + status);
}
});
}
function computeTotalDistance(result){
var total = 0, myroute = result.routes[0];
for(var i=0,l=myroute.legs.length; i<l; i++){
total += myroute.legs[i].distance.value;
}
for(var i=0,l=myroute.overview_path.length; i<l; i++){
// should be a LatLng object at each iteration
console.log(myroute.overview_path[i]);
}
total = total / 1000;
document.getElementById('total').innerHTML = total + ' km';
}