Draw Path using Google Maps Javascript API

by Vincy. Last modified on July 9th, 2022.

In this tutorial, we are going to see how to draw a path between multiple locations on a map using Google Maps Javascript API. In a previous tutorial, we have seen example code for adding markers on the map layer.

In this example, I add markers to point locations and connect the points by drawing the path between the locations. This path will show the flight plan to cover the locations plotted on the map.

In this code, I have used the Polyline class of the Google Maps API. This class is used to draw pathways on the map layer between the path coordinates.

I get the list of countries from the database and compute the location coordinates each country using Google Map GeoCoding service. These locations are pushed into an array that will be passed as the path coordinates parameter of the Polyline class to draw the path.

Accessing Google Map API via Javascript to Draw Path

The following Javascript is used to get the latitude and the longitude coordinates of the countries read from the database. This code is same as we have seen while adding markers on the map in the previous tutorial.

Show-Path-on-Google-Map-using-Javascript-API-Output

These coordinates are pushed into a location array on each iteration.

I have defined a function to call Google Polyline class to draw the path between the location coordinates of the countries. I invoked this function, once all the country results are iterated and their coordinates are stored in an array.

This function used the array of path coordinates to draw the path.

<script>
	var map;
	var pathCoordinates = Array();
	function initMap() {
		var countryLength
		var mapLayer = document.getElementById("map-layer");
		var centerCoordinates = new google.maps.LatLng(37.6, -95.665);
		var defaultOptions = {
			center : centerCoordinates,
			zoom : 4
		}
		map = new google.maps.Map(mapLayer, defaultOptions);
		geocoder = new google.maps.Geocoder();
		<?php
            if (! empty($countryResult)) {
            ?>
		countryLength = <?php echo count($countryResult); ?>
		<?php
                foreach ($countryResult as $k => $v) 
                {
            ?>
		geocoder.geocode({
			'address' : '<?php echo $countryResult[$k]["country"]; ?>'
		}, function(LocationResult, status) {
			if (status == google.maps.GeocoderStatus.OK) {
				var latitude = LocationResult[0].geometry.location.lat();
				var longitude = LocationResult[0].geometry.location.lng();
				pathCoordinates.push({
					lat : latitude,
					lng : longitude
				});

				new google.maps.Marker({
					position : new google.maps.LatLng(latitude, longitude),
					map : map,
					title : '<?php echo $countryResult[$k]["country"]; ?>'
				});

				if (countryLength == pathCoordinates.length) {
					drawPath();
				}

			}
		});
		<?php
                }
            }
            ?>
	}
	function drawPath() {
		new google.maps.Polyline({
			path : pathCoordinates,
			geodesic : true,
			strokeColor : '#FF0000',
			strokeOpacity : 1,
			strokeWeight : 4,
			map : map
		});
	}
</script>
<script async defer
	src="https://maps.googleapis.com/maps/api/js?key=<?php echo API_KEY; ?>&callback=initMap">
	
</script>

Download

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page