Geocoding Addresses with Google Maps API

G
Published in: Google Maps - Javascript

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.");
      }
    });
  }
}
📮  Subscribe to our Email Newsletter for Google tips and tutorials!
Published in: Google Maps - Javascript

Looking for something? Find here!

Meet the Author

Web Geek, Google Developer Expert
A
Amit Agarwal

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. He is the developer of Mail Merge for Gmail and Document Studio. Read more on Lifehacker and YourStory

Get in touch

Google Add-ons

Do more with your Gmail and GSuite account
G

We build bespoke solutions that use the capabilities and the features of Google Workspace for automating business processes and driving work productivity.

  1. Mail Merge with Attachments
    Send personalized email to your Google Contact with a Google Sheet and Gmail
  2. Save Emails and Attachments
    Download email messages and file attachments from Gmail to your Google Drive
  3. Google Forms Email Notifications
    Send email notifications to multiple people when a new Google Form is submitted
  4. Document Studio
    Create beautiful pixel perfect documents merging data from Google Sheets and Google Forms
  5. Creator Studio for Google Slides
    Turn your Google Slides presentations into animated GIFs and videos for uploading to YouTube