Adding Custom Markers on Map using Google Maps Javascript API

Adding custom marker on the map layer will be useful to show custom information with iconic representation as per the user interest. For example,  if the user wants to mark census data then the custom markers can be used instead of the default map markers to show the variations in the population strength.


In this tutorial, I have marked the countries location with the custom icon. I have used the countries flag as the custom markers to locate the country. In a previous tutorial, I have added an example for adding default map markers for the list of countries by using Google Maps JavaScript API. In this example, it has a database table with a list of countries and custom markers. I retrieve the database result and iterate to plot the countries location on the map layer with custom markers.

Javascript Code for Map initialization and Adding Custom Markers

The following code will show how to initialize a map object of Google Map API. In this code, I request the geo-coordinates by sending the country name to the Google GeoCoder service. While initializing the Google map Marker, the latitude and the longitude coordinates are used for positioning the countries on the map. Also, the path of the custom markers stored in the database is used to set the “icon” option to replace the default marker.

    src="<?php echo API_KEY; ?>&callback=initMap"
    async defer></script>

	var map;
	var geocoder;
	function initMap() {

		var mapLayer = document.getElementById("map-layer");
		var centerCoordinates = new google.maps.LatLng(40.4637, 3.7492);
		var defaultOptions = {
			center : centerCoordinates,
			zoom : 2

		map = new google.maps.Map(mapLayer, defaultOptions);
		geocoder = new google.maps.Geocoder();

		if (! empty($countryResult)) {
		    foreach ($countryResult as $k => $v) {
			'address' : '<?php echo $countryResult[$k]["country_name"]; ?>'
		}, function(LocationResult, status) {
			if (status == google.maps.GeocoderStatus.OK) {
				var latitude = LocationResult[0];
				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_name"]; ?>',
				icon : 'marker/<?php echo $countryResult[$k]["marker"]; ?>'

Output – Custom Markers on Google Maps

This screenshot shows the output after adding custom markers on the map layer using Google Maps Javascript API.



This PHP code tutorial was published on December 27, 2017.

↑ Back to Top