Skip to content

Instantly share code, notes, and snippets.

@abnersajr
Last active October 16, 2022 00:09
Show Gist options
  • Save abnersajr/de662115086d40f115a7 to your computer and use it in GitHub Desktop.
Save abnersajr/de662115086d40f115a7 to your computer and use it in GitHub Desktop.
Trace Route using Maps API Javascript V3
function traceRouteMap() {
var mapElement = document.getElementById('google-map');
var directionsService = new google.maps.DirectionsService();
var startLatLng = new google.maps.LatLng(-29.687306,-53.815477);
var directionsDisplay= new google.maps.DirectionsRenderer();
var geocoder = new google.maps.Geocoder();
var markers = [];
var center;
var mapOptions = {
zoom: 12,
center: startLatLng,
scrollwheel: false
};
var map = new google.maps.Map(mapElement, mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setOptions({ suppressMarkers: true });
var marker = new google.maps.Marker({
map: map,
draggable: false,
animation: google.maps.Animation.DROP,
position: startLatLng,
icon: "/static/images/pin_map.png"
});
//Add marker to Push Array to count after route show
markers.push(marker);
//Trigger Form Submit
$('#google-form').on('submit', function() {
event.preventDefault();
var address = $('#google-address').val();
//Get LatLng based on address entered
geocoder.geocode( { 'address': address}, function(results, status) {
//If get LatLng based on address
if (results.length) {
var request = {
origin : results[0].geometry.location,
destination : startLatLng,
travelMode : google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(result, status) {
// IF OK and have Route to show
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
if(markers.length > 1) {
markers[1].setMap(null);
markers.splice(1,1);
}
var marker2 = new google.maps.Marker({
position: result.routes[0].legs[0].start_location,
map: map,
icon: '/static/images/pin_map.png'
});
markers.push(marker2);
$('.retorno-mapa').html('');
} else {
$('.retorno-mapa').html('Não foi possível montar um trajeto.');
}
});
} else {
$('.retorno-mapa').html('Ocorreu um problema, reveja seu endereço ou tente novamente.');
}
});
return false;
});
google.maps.event.addDomListener(window, "resize", function() {
var center = map.getCenter();
google.maps.event.trigger(map, "resize");
map.setCenter(center);
});
}
function loadScript(callBack) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp' +
'&signed_in=true&language=pt-BR&callback='+callBack;
document.body.appendChild(script);
}
if($('#google-map').length) {
window.onload = loadScript('traceRouteMap');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment