Add Markers to Show Locations on Google Maps

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

Google Map Javascript API provides geographical data based on the request sent via the client side script. In a previous tutorial, we have seen how to get the Google Map resource and to plot the current location of the user.

In this tutorial, we are going to see how to add markers to show an array of locations on the Google Map.

In this example, I have read locations from a country database containing the number of country names. I iterate the country results and get the latitude and longitude co-ordinate using Google Map GeoCoding Service.

Using the location co-ordinates I have added markers to locate the countries on the Map. On mouse over the map marker, I have shown a tooltip with the country name by setting the title parameter.

Read Country Names From the Database

This PHP code connects the database using DBController class and reads the country names into an array. This array of results are used to get the location coordinates using which we can add map markers.

add-markers-to-show-locations-in-google-maps-output

<?php

require("DBController.php");

$dbController = new DBController();

$query = "SELECT * FROM tbl_country";
$countryResult = $dbController->runQuery($query);

?>

Javascript to Add Location Markers on the Google Map

The following Javascript code is used to get the location coordinates for the country name which is retrieved from the database. I iterated the database result and get the latitude and the longitude coordinates of the country on each iteration of the loop using the Google Map GeoCoding service.

Then, these location data will be used to plot the country location on the map with a marker. The mouseover event on the marker will show the country name with a tooltip.

<script
		src="https://maps.googleapis.com/maps/api/js?key=<?php echo API_KEY; ?>&callback=initMap"
		async defer></script>

	<script type="text/javascript">
	var map;
	var geocoder;		

	function initMap() {
		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)) {
		    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();
						} 
		        	    		new google.maps.Marker({
		            	        position: new google.maps.LatLng(latitude, longitude),
		            	        map: map,
		            	        title: '<?php echo $countryResult[$k]["country"]; ?>'
		            	    });
					});
			    <?php
		    }
		}
		?>		
	}
	</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