In a multi-location application, I have a button for calling a route between two points using the setDirection function, as inserted below.
I would like support to be able to remove a route traced earlier after clicking on another marker.
// Funções de roteamento
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
function setDirection(destLat, destLng) {
directionsDisplay = new google.maps.DirectionsRenderer({ polylineOptions:{strokeColor:"#4a4a4a",strokeWeight:5}, suppressMarkers:true });
directionsDisplay.setMap(map);
var request = {
origin: pos.lat + ',' + pos.lng,
destination: destLat + ', ' + destLng,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function (result, status) {
console.log(request);
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});
return false;
}
Below I have inserted a function that shows the map, including the section where you have the button to "Trace the Route"
// Recarrega marcadores
function reloadMarkers() {
var center = map.getCenter();
setMapOnAll(null);
map.setCenter(center);
downloadUrl(findUrl, pos, function (data) {
var xml = data;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getElementsByTagName("name")[0].firstChild.nodeValue;
var address = markers[i].getElementsByTagName("address")[0].firstChild.nodeValue;
var type = markers[i].getElementsByTagName("type")[0].firstChild.nodeValue;
var point = new google.maps.LatLng(
parseFloat(markers[i].getElementsByTagName("lat")[0].firstChild.nodeValue),
parseFloat(markers[i].getElementsByTagName("lng")[0].firstChild.nodeValue));
var html = "<b>" + name + "</b> <br/>" + address +
'<br><a href="#" onclick="return setDirection(' + markers[i].getElementsByTagName("lat")[0].firstChild.nodeValue + ',' + markers[i].getElementsByTagName("lng")[0].firstChild.nodeValue + ');">Traçar Rota</a>';
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
This is the button where I return the 'setDirection ()' function:
<a href="#" onclick="return setDirection(' + markers[i].getElementsByTagName("lat")[0].firstChild.nodeValue + ',' + markers[i].getElementsByTagName("lng")[0].firstChild.nodeValue + ');">Traçar Rota</a>