Google Maps: Create New Marker on Clicking the Map

This article shows how to create a new marker whenever you click or double click on the Google Map.

In previous article, we had seen how we can Display Google Map with Marker when we have latitude and longitude value.

Here, we will be using the same code and adding a new functionality of displaying a new marker whenever users double click on the map. You can also add this functionality on “single click” instead of “double click” event. I will be showing both in the example code below.

If we are using double click event to create new marker, then we can disable zoom on double click. By default, the map zooms when you double click on it. You can disable this by using the option disableDoubleClickZoom: true.

Here is the full source code:

Note that: At the bottom of the code there is a script src included. You need to put your API Key over there like this:
https://maps.googleapis.com/maps/api/js?key=xxxxxxxxxxxxxxxxxxxx&callback=initMap
You can get the API key from here: Get API Key


<html>
	<head>
		<title>Google Map</title>
		<meta name="viewport" content="initial-scale=1.0">
		<meta charset="utf-8">
		<style>		  
		  #map { 
			height: 300px;	
			width: 600px;			
		  }		  
		</style>		
	</head>	
	<body>		
		<div style="padding:10px">
			<div id="map"></div>
		</div>
		
		<script type="text/javascript">
		var map;
		
		function initMap() {							
			var latitude = 27.7172453; // YOUR LATITUDE VALUE
			var longitude = 85.3239605; // YOUR LONGITUDE VALUE
			
			var myLatLng = {lat: latitude, lng: longitude};
			
			map = new google.maps.Map(document.getElementById('map'), {
			  center: myLatLng,
			  zoom: 14,
			  disableDoubleClickZoom: true, // disable map zoom on double click
			});
					
			var marker = new google.maps.Marker({
			  position: myLatLng,
			  map: map,
			  //title: 'Hello World'
			  
			  // setting latitude & longitude as title of the marker
			  // title is shown when you hover over the marker
			  title: latitude + ', ' + longitude 
			});	
			
			// Create new marker on double click event on the map
			google.maps.event.addListener(map,'dblclick',function(event) {
                var marker = new google.maps.Marker({
				  position: event.latLng, 
				  map: map, 
				  title: event.latLng.lat()+', '+event.latLng.lng()
				});                
            });
            
            // Create new marker on single click event on the map
			/*google.maps.event.addListener(map,'click',function(event) {
                var marker = new google.maps.Marker({
				  position: event.latLng, 
				  map: map, 
				  title: event.latLng.lat()+', '+event.latLng.lng()
				});                
            });*/
		}
		</script>
		<script src="https://maps.googleapis.com/maps/api/js?key=YOUR-API-KEY&callback=initMap"
		async defer></script>
	</body>	
</html>

Hope this helps. Thanks.