Here is the general recipe:
You need to extract the coordinates of the route from the JSON response.
These are in the response at 2 levels of detail.
The explicit coordinates of the major intersections along the route. You can read these in plain English and you can extract them as associative array members.
In addition to above, there is a coded string containing lots more (lat, lon)
pairs of the points between the intersections. You have to decode these and there is an algorithm available. (I did a PHP version a few weeks ago and link is below). BTW the reason for this second array is this: Imagine a long winding country road with no intersections... this array will follow the road curves, giving (lat,lon)
pairs not found in 1.
3). Build an array of coordinates (from 1 and including 2 if you need finer detail).
4) Then use code like below (stolen from below link and adjusted a bit: https://developers.google.com/maps/documentation/javascript/examples/polyline-simple:) that shows you how to draw the lines on a map.
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: {lat: 0, lng: -180},
mapTypeId: 'terrain'
});
var routeCoordinates = [ // put your array here
{lat: 37.772, lng: -122.214},
{lat: 21.291, lng: -157.821},
{lat: -18.142, lng: 178.431},
{lat: -27.467, lng: 153.027}
];
var routePath = new google.maps.Polyline({
path: routesCoordinates,
geodesic: true,
strokeColor: '#FF0000', // adjust line colour
strokeOpacity: 1.0, // adjust line opacity
strokeWeight: 2 // adjust line thickness
});
routePath.setMap(map);
}
</script>
The example at the google link shows you how to do the tiny bit a HTML involved etc.
Now for the good bit to decode the polyline points:
Get itinerary latitudes & longitude from google maps with PHP
In above the function decodePolylinePoints($pointsString)
returns an array of (lat,lons)
that you can use for drawing the route.
You need to study the JSON
to understand the code, and while it looks messy its perfectly logical. Put the JSON
in an editor like VSCode and it will be displayed properly formatted.