Adding Markers onClick in Google Map v3

If you are wondering how to add markers on Google Map, here’s the simple Javascript snippet that adds dragable marker on Google Map. Just click on Drop Marker button to drop marker on the Map. You need to obtain Google Map API key and replace “GOOGLE-MAP-API-KEY” with yours, read this documentation to know how to obtain API Key. For more advance tutorial click here.
HTML
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
<!DOCTYPE html>
<html>
  <head>
    <style type="text/css">
      #google_map {width: 550px; height: 450px;margin-top:50px;margin-left:auto;margin-right:auto;}
    </style>
    <script type="text/javascript"
      src="//maps.googleapis.com/maps/api/js?key=GOOGLE-MAP-API-KEY&#038;sensor=false">
    </script>
    <script type="text/javascript">

      var mapCenter = new google.maps.LatLng(54.19265, 16.1779); //Google map Coordinates
	  var map
	  function initialize() //function initializes Google map
	  {
		var googleMapOptions =
		{
			center: mapCenter, // map center
			zoom: 15, //zoom level, 0 = earth view to higher value
			panControl: true, //enable pan Control
			zoomControl: true, //enable zoom control
			zoomControlOptions: {
				style: google.maps.ZoomControlStyle.SMALL //zoom control size
			 },
			scaleControl: true, // enable scale control
			mapTypeId: google.maps.MapTypeId.ROADMAP // google map type
        };
		map = new google.maps.Map(document.getElementById("google_map"), googleMapOptions);
      }

	  	function addMyMarker() { //function that will add markers on button click
			var marker = new google.maps.Marker({
				position:mapCenter,
				map: map,
				  draggable:true,
				  animation: google.maps.Animation.DROP,
				title:"This a new marker!",
              icon: "http://maps.google.com/mapfiles/ms/micons/blue.png"
			});
		}
    </script>
  </head>

  <body onLoad="initialize()">
    <div id="google_map" ></div><button id="drop" onClick="addMyMarker()">Drop Markers</button>
  </body>
</html>

Demo

map loading
  • 5 Comments

    Add Comment
    • Paolo
      Hi, I have 2 problems I hope you help me to solve because I really need your fantastic short script . 1 - I get my API key for browsers and for my domain but when try to run it always same message: Google disabled the use of API of Google Maps for this application... ecc ecc 2 - How can I store the lang and long in my mysql database when I finish to point my marker? Hope you will help me, Thanks
    • Json
      Thousand thanks to your example. It works well on my html5 page as well as in phonegap build.
    • Dan
      Hi! Is it possible to retain the pins? So that when multiple users go to the site, they are able to see other peoples pins?
    • Tony Vigil
      Saran, I tried this with a button in a different frame, but it didn't work. What needs to be added to make that work?