Sitemap

Getting the Google Maps Traffic API to a Customized Web Application

3 min readJul 5, 2023

--

Press enter or click to view image in full size

Scope
This project will implement live traffic data through Google Maps API in a web application.
Scenario
The user can see the live condition of the traffic, search for places, and draw routes to check the underlying traffic conditions and toggle the route (hide/show).

Variables: The code begins by declaring several variables (map, directionsService, directionsDisplay, currentRoute, and trafficLayer) using the var keyword. These variables will store references to various components and data related to the map and directions.

initMap() function: This function is the callback function for the Google Maps API and is executed when the API finishes loading. The map is initialized inside this function with specific options, including the center coordinates, zoom level, and custom map styles. The traffic layer, directions service, and directions renderer are also set up. Event listeners for the search form, directions form, and toggle button are also attached.

getDirections(event) function is executed when the directions form is submitted. It prevents the default form submission behavior, retrieves the origin and destination inputs, creates a DirectionsRequest object with the provided inputs and the travel mode (driving in this case), and sends the request to the directions service. If the response status is successful (google.maps.DirectionsStatus.OK), the directions are displayed on the map, and the step-by-step instructions are appended to the directionsResultDiv element.

Get Milad Korde Ph.D.’s stories in your inbox

Join Medium for free to get updates from this writer.

toggleRoute() function: This function is executed when clicking the toggle button. It checks if the directionsDisplay is set and determines whether to show or hide the route on the map by setting the display map property accordingly.

performSearch(event) function is executed when the search form is submitted. It prevents the default form submission behavior, retrieves the search input, and uses the Google Maps Geocoder to convert the input into geographic coordinates. If the geocoding is successful, the map is centered on the location, and a marker is placed at that position.

window.onload = initMap;: This line assigns the initMap function as the callback function to be executed when the window (or the entire page) finishes loading. It ensures the map and associated functionalities are set up when the page is ready.

Overall, this code sets up a map with specific options, integrates various Google Maps services (such as directions and geocoding), and provides user interactivity for searching locations, getting directions, and toggling the visibility of the route on the map.

<script>
var map;
var directionsService;
var directionsDisplay;
var currentRoute;
var trafficLayer;
//var routeVisible = false;


function initMap() {
var mapOptions = {
center: { lat: 30.267153, lng: -97.743057 },
zoom: 12,
styles: [
// Custom map styles here
// Example:
{
featureType: "all",
elementType: "all",
stylers: [
{ invert_lightness: true },
{ saturation: -100 },
{ lightness: 0 },
{ visibility: "on" },
],
},
],
};
map = new google.maps.Map(document.getElementById("map"), mapOptions);

var legendContainer = document.getElementById("legend");
map.controls[google.maps.ControlPosition.LEFT_BOTTOM].push(legendContainer);

trafficLayer = new google.maps.TrafficLayer();
trafficLayer.setMap(map);

directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay.setMap(map);

var searchForm = document.getElementById("search-form");
searchForm.addEventListener("submit", performSearch);

var directionsForm = document.getElementById("directions-form");
directionsForm.addEventListener("submit", getDirections);

var toggleButton = document.getElementById("toggle-button");
toggleButton.addEventListener("click", toggleRoute);


function getDirections(event) {
event.preventDefault();
var originInput = document.getElementById("origin-input").value;
var destinationInput = document.getElementById("destination-input").value;
var request = {
origin: originInput,
destination: destinationInput,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(result, status) {
if (status === google.maps.DirectionsStatus.OK) {
currentRoute = result;
directionsDisplay.setDirections(result);
var directionsResultDiv = document.getElementById("directions-result");
directionsResultDiv.innerHTML = "";
var directionsResultText = document.createElement("div");
directionsResultText.innerHTML = "<strong>Directions:</strong>";
directionsResultDiv.appendChild(directionsResultText);
var steps = result.routes[0].legs[0].steps;
for (var i = 0; i < steps.length; i++) {
var stepText = document.createElement("div");
stepText.innerHTML = "<div style='font-size: 0.9em'>" + steps[i].instructions + "</div>";
directionsResultDiv.appendChild(stepText);
}
// Show the route by default
directionsDisplay.setMap(map);
routeVisible = true;
} else {
console.log("Error occurred while retrieving directions:", status);
}
});
}


function toggleRoute() {
if (directionsDisplay) {
if (directionsDisplay.getMap()) {
directionsDisplay.setMap(null); // Hide the route on the map
} else {
directionsDisplay.setMap(map); // Show the route on the map
}
}
}



}


function performSearch(event) {
event.preventDefault();
var searchInput = document.getElementById("search-input").value;
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ address: searchInput }, function(results, status) {
if (status === google.maps.GeocoderStatus.OK && results.length > 0) {
var location = results[0].geometry.location;
map.setCenter(location);
new google.maps.Marker({
map: map,
position: location
});
} else {
console.log("No results found for the search query.");
}
});
}


// Initialize the map on page load
window.onload = initMap;

</script>

You can check the result at https://miladmak.github.io/.

--

--

Milad Korde Ph.D.
Milad Korde Ph.D.

Written by Milad Korde Ph.D.

An experienced GIS data scientist. I provide open-source and ArcGIS-based solutions, statistical approaches, and significant changes in geospatial data!