Draw Path using Google Maps Javascript API

In this educationalwe are going to see the way to draw a route among more than one locations on a map the use of Google Maps Javascript API. In a preceding educationalwe have visible example code for including markers on the map layer. In this situation, I add markers to point locations and join the factors via drawing the direction among the locations. This route will show the flight plan to cowl the places plotted on the map.

 

Accessing Google Map API via Javascript to Draw Path

The following Javascript is used to get the range and the longitude coordinates of the study of the nation from the database. This code is same as we have seen even as including markers at the map inside the preceding educationalthese coordinates are driven into a vicinity array on every iteration.

I’ve defined a feature to call Google Polyline class to draw the direction between the region coordinates of the countries. I invoked this functiononce all u . s . consequences are iterated and their coordinates are stored in an array. This function used the array of direction coordinates to draw the course.

<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>

Show Path on Google Map using Javascript API – Output

Please follow and like us:



Leave a Comment

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