Getting latitude and longitude from google maps api

Posted on August 12, 2015 by Suresh Kamrushi in Javascript

As a client requirement I need to get latitude and longitude of the user on clicking of map. Google API is the best option which can be configure very easily into your application and easy to add/modify.

So I thought of sharing so someone will get something out of it.
Here I am sharing same code…
Create HTML file as “latlong.html” and add the below code inside “<head>” tag

<script src="" type="text/javascript"></script>
<script type="text/javascript">
 window.onload = function () {
 var mapOptions = {
 center: new google.maps.LatLng(17.3828, 78.4815),
 zoom: 14,
 mapTypeId: google.maps.MapTypeId.ROADMAP
 var infoWindow = new google.maps.InfoWindow();
 var latlngbounds = new google.maps.LatLngBounds();

 //This will load your map with default location co-ordinates.
 var map = new google.maps.Map(document.getElementById("mapDiv"), mapOptions);

 //To capture click event.
 google.maps.event.addListener(map, 'click', function (e) {
 document.getElementById("latitude").value =;
 document.getElementById("longitude").value = e.latLng.lng();
//Adding marker on click
var marker;
function placeMarker(location,map) {
  if ( marker ) {
  } else {
    marker = new google.maps.Marker({
      position: location,
      map: map

On page load here we are loading the google API file and the default location (17.3828, 78.4815). Additionally are we are handling the click event to capture latitude and longitude and setting the marker.

Now you need to set HTML as below. Copy below HTML and past inside body tag.

<div id="dvMap" style="width: 300px; height: 300px"> <div>
<input id="latitude" name="latitude" type="text">
<input id="longitude" name="longitude" type="text">

Now if you access the page in browser map will get render with 300 height and width. And on click on any location text boxes get filled with latitude and longitude.