Geocoding Addresses with Google Maps API

The reverse geocoding feature of Google Maps API lets you convert latitude and longitude into a physical address. Here’s a snippet of code that implements address lookup in Google Maps using JavaScript.

//Initialize Global Variables
var adUnit;
var marker;
var infoWindow;
var geocoder;
var map = null;
var lat;
var lon;

function initialize() {
  var mapOptions = {
    zoom: 16,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    streetViewControl: false,
    panControl: false,
    mapTypeControl: true,
    mapTypeControlOptions: {
      style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
      position: google.maps.ControlPosition.BOTTOM_CENTER,
    },
    zoomControl: true,
    zoomControlOptions: {
      style: google.maps.ZoomControlStyle.SMALL,
      position: google.maps.ControlPosition.LEFT_CENTER,
    },
  };

  map = new google.maps.Map(document.getElementById('map'), mapOptions);
  var adUnitDiv = document.createElement('div');
  var adsense = 'ca-pub-1234';

  // Add a Google AdSense unit
  var adUnitOptions = {
    format: google.maps.adsense.AdFormat.BUTTON,
    position: google.maps.ControlPosition.RIGHT_BOTTOM,
    publisherId: adsense,
    map: map,
    visible: true,
  };

  var adUnit = new google.maps.adsense.AdUnit(adUnitDiv, adUnitOptions);

  lat = 37.41954708018655;
  lon = -122.08398342132568;

  // Determine your initial location through GPS
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function (position) {
      lat = position.coords.latitude;
      lon = position.coords.longitude;
    });
  }

  var latLng = new google.maps.LatLng(lat, lon);
  map.setCenter(latLng);
  marker = new google.maps.Marker({
    position: latLng,
    title: 'Drag this pin to another location',
    animation: google.maps.Animation.DROP,
    map: map,
    draggable: true,
  });

  infoWindow = new google.maps.InfoWindow({
    content:
      "<div class='place'>Drag this pin anywhere on the Google Map to know the approximate address of that point.</div>",
  });

  infoWindow.open(map, marker);

  geocoder = new google.maps.Geocoder();

  //Update postal address when the marker is dragged
  google.maps.event.addListener(marker, 'dragend', function () {
    geocoder.geocode({ latLng: marker.getPosition() }, function (responses) {
      if (responses && responses.length > 0) {
        infoWindow.setContent(
          "<div class='place'>" +
            responses[0].formatted_address +
            '<br /> <small>' +
            'Latitude: ' +
            marker.getPosition().lat() +
            '<br>' +
            'Longitude: ' +
            marker.getPosition().lng() +
            '</small></div>'
        );
        infoWindow.open(map, marker);
      } else {
        alert('Error: Google Maps could not determine the address of this location.');
      }
    });
    map.panTo(marker.getPosition());
  });

  // Close the marker window when being dragged
  google.maps.event.addListener(marker, 'dragstart', function () {
    infoWindow.close(map, marker);
  });
}

google.maps.event.addDomListener(window, 'load', initialize);

// Search for an address on Google Maps
function showAddress(address) {
  if (geocoder) {
    geocoder.geocode({ address: address }, function (results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        // For accurate addresses, the type is ROOFTOP else APPROXIMATE
        if (results[0].geometry.location_type == 'ROOFTOP') map.setZoom(18);
        else map.setZoom(14);
        map.setCenter(results[0].geometry.location);
        marker.setPosition(results[0].geometry.location);
        infoWindow.open(map, marker);
      } else {
        alert('Error: ' + address + ' cannot be found on Google Maps.');
      }
    });
  }
}
Amit Agarwal

Amit Agarwal

Google Developer Expert, Google Cloud Champion

Amit Agarwal is a Google Developer Expert in Google Workspace and Google Apps Script. He holds an engineering degree in Computer Science (I.I.T.) and is the first professional blogger in India.

Amit has developed several popular Google add-ons including Mail Merge for Gmail and Document Studio. Read more on Lifehacker and YourStory

0

Awards & Titles

Digital Inspiration has won several awards since it's launch in 2004.

Google Developer Expert

Google Developer Expert

Google awarded us the Google Developer Expert award recogizing our work in Google Workspace.

ProductHunt Golden Kitty

ProductHunt Golden Kitty

Our Gmail tool won the Lifehack of the Year award at ProductHunt Golden Kitty Awards in 2017.

Microsoft MVP Alumni

Microsoft MVP Alumni

Microsoft awarded us the Most Valuable Professional (MVP) title for 5 years in a row.

Google Cloud Champion

Google Cloud Champion

Google awarded us the Champion Innovator title recognizing our technical skill and expertise.

Email Newsletter

Sign up for our email newsletter to stay up to date.

We will never send any spam emails. Promise.