Find Driving Directions, Distance and Time with Google Maps API and Apps Script

Use Google Apps Script with the Google Maps API to find the driving distance, time and the driving route between any two points. The origin and destination may either be specified as plain text or you can specify the latitude and longitude coordinates. Google Maps API can fetch directions for WALKING, DRIVING and BICYCLING modes.

function GoogleMapsAPI () {
  // Written by Amit Agarwal
  // Web:

  var origin = "10 Hanover Square, NY 10005";
  var destination = "Times Square";
  var travelMode = Maps.DirectionFinder.Mode.WALKING;
  var directions = Maps.newDirectionFinder()
  if (directions.status !== "OK") 
    return "Error: " + directions.status;
  var route = directions.routes[0].legs[0];
  var time = route.duration.text;
  var distance = route.distance.text;
  var steps = {
    return step.html_instructions.replace(/<[^>]+>/g, "")


Google Maps Functions for Google Spreadsheets and Apps Script

The Maps Service of Google Apps lets you reverse-geocode and geocode postal addresses without using the Google Maps API. Given the latitude and longitude, you can get the link to the place on Google Map, it can get the formatted street address with City & zip from the geo coordinates or vice-versa. Credit: @thomasfr

These geo-functions can be used inside Google Spreadsheets and also Google Scripts as in the Twitter Archiver that puts the geo-tagged tweets on a Google Maps.

/* Get the Google Maps Link */
/* The longitude and latitude are passed as a comma separated string */
function getGoogleMapsLink(longLat) {
  return ""+longLat;

/* Get the Postal Address from geo location */
function getStreetAddress(longLat) {
  var longLat = longLat.split(',');
  var response = Maps.newGeocoder().reverseGeocode(longLat[0], longLat[1]);
  if(response.status === "OK") {
    return response.results[0].formatted_address;
  return null;

/* Get the latitude, longitude from the postal address */
function geocode(address) {
    var response = Maps.newGeocoder().setRegion('com').geocode(address);
    var longLat = {};
    var l;
    Logger.log("address: " + address);
    if (response.status === "OK") {
      Logger.log("response " + JSON.stringify(response));
      if((l = response.results[0].geometry.location)) {
        longLat.lng = l.lng; =;
        return longLat;
    else {
      return "error";

Embed Street View with Google Maps API

The Embed Google Maps app uses the Google Maps API (v3) to generate the embed code for placing street view and satellite images in your website.

When you open the app, it centers the Google Map around your current geolocation. As you zoom or pan the map, the Street View location and Point-of-View, specifically zoom, pitch and heading, are appended to the IFRAME url.

Heading defines the rotation angle around the camera locus while pitch defines the angle variance “up” or “down” from the camera’s initial default pitch.

var map, pano, lat = 40.7045737,
    lng = -74.0089673;

function generateURL(parameters) {

    var url = "" + parameters,
        iframe = '';

    document.getElementById("embed-code").value = iframe.replace("URL", url);
    document.getElementById("link").href = url;

function updateSV() {

    var parameters,
        pov = pano.getPov(),
        pos = pano.getPosition();

    if (pos) {
        lat =;
        lng = pos.lng();

    parameters = "street|" + pov.zoom + "|" + pov.heading + "|" + pov.pitch + "|" + lat + "|" + lng;



function updateMap() {

    var center = map.getCenter();
    generateURL(map.getMapTypeId() + "|" + map.getZoom() + "|" + + "|" + center.lng());

function initialize() {

    var input, autocomplete,
        mapOptions = {
            zoom: 16,
            center: new google.maps.LatLng(lat, lng),
            streetViewControl: true,
            panControl: true,
            scaleControl: true,
            mapTypeId: "roadmap"

    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

    input = document.getElementById('pac-input');

    google.maps.event.addListener(map, 'maptypeid_changed', updateMap);
    google.maps.event.addListener(map, 'idle', updateMap);

    pano = map.getStreetView();

    google.maps.event.addListener(pano, 'visible_changed', updateSV);
    google.maps.event.addListener(pano, 'position_changed', updateSV);
    google.maps.event.addListener(pano, 'links_changed', updateSV);
    google.maps.event.addListener(pano, 'pano_changed', updateSV);
    google.maps.event.addListener(pano, 'pov_changed', updateSV);

    autocomplete = new google.maps.places.Autocomplete(input);
    autocomplete.bindTo('bounds', map);

    google.maps.event.addListener(autocomplete, 'place_changed', function () {

        var place = autocomplete.getPlace();

        if (!place.geometry) {

        if (place.geometry.viewport) {
        } else {


    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function (position) {
            map.setCenter(new google.maps.LatLng(position.coords.latitude,


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

Find Distance Between Two Points with Apps Script

Curious to know how far is location A from location B? You can put the two places in separate cells in a Google Spreadsheet and then use the getDirection() function to find the distance between the two place in miles or kilometers.

Internally, it uses the Google Maps service of Apps Script to find the distance and directions between the two points. You can also use the getMileage() function to calculate the “as the crow flies” distance between any two latitude and longitude co-ordinates.

/* Credit: */
function getDirection(city1, city2) {

 var directions = Maps.newDirectionFinder()
 var d = directions.routes[0].legs[0].distance.text;
  return parseInt(d.split(" ")[0].replace(",", ""));;

function getMileage(city1, city2) {
  var p1 = Maps.newGeocoder().geocode(city1);
  var p2 = Maps.newGeocoder().geocode(city2);
  return getDistance(getCoordinates(p1), getCoordinates(p2), opt);

function getCoordinates(point) {
  var result = point.results[0].geometry.location;
  return {"lng": result.lng, "lat":} 

function getDistance(c1, c2, opt) {
  var lat1 = rad(, lat2 = rad(;
  var lng1 = rad(c1.lng), lng2 = rad(c2.lng);
  var dLng = (lng2-lng1), dLat = (lat2-lat1);
  var R = 6371/1.6;
  var a = Math.sin(dLat/2) * Math.sin(dLat/2) + 
    Math.sin(dLng/2) * Math.sin(dLng/2) * 
    Math.cos(lat1) *  Math.cos(lat2); 
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
  return parseInt(R * c);

function rad(degrees) {
  return degrees * Math.PI/180;

Find People’s Location through Google Maps

The Where Am I and Postal Address apps using the HTML5 Geolocation service and Google Maps’ Geocoder service to determine your accurate physical location up to the zip code.

The HTML5 geolocation service returns the current longitude and latitude coordinates which are then passed to Google Geocoder for determining the actual geographic location including the street address and the pin code.

This can be used by shopping websites to serve store results that are nearest to the visitor’s current location, by banks for showing the location of nearest ATMs, gas stations and so on.

HTML – We are including the jQuery library and the Google Maps API for geocoding the location.

    Where Am I
Postal Address
Zip Code

When the user click the Where Am I link, the browser ask for permissions to share his or her location with the website. If they say Allow, the co-ordinates are passed to the Google Maps API for determining the physical address.

$(function () {
    $("#showMyLocation").click(function (event) {
        $(this).html('Determining address...');
        navigator.geolocation.getCurrentPosition(function (position) {
            var geocoder = new google.maps.Geocoder();
            var latLng   = new google.maps.LatLng( 
                position.coords.latitude, position.coords.longitude);
                'latLng': latLng
            }, function (results, status) {
                for (var i = 0; i < results[0].address_components.length; i++) {
                    var address = results[0].address_components[i];
                    if (address.types[0] == "postal_code") {
        return false;

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);
    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: "
Drag this pin anywhere on the Google Map to know the approximate address of that point.
" });, 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( "
" + responses[0].formatted_address + "
" + "Latitude: " + marker.getPosition().lat() + "
" + "Longitude: " + marker.getPosition().lng() + "
" );, 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);, marker); } else { alert("Error: " + address + " cannot be found on Google Maps."); } }); } }

Geocoding Postal Addresses with Google Maps API

Let’s say you have a bunch of postal address in a spreadsheet and you wish to geocode these addresses (get the latitude and longitude information).

While there are several web apps available that that can geocode addresses, one of the easier options is available inside Google Apps Script.

Just past the list of postal address in a column in Google Docs spreadsheet and then run the following Google Apps Script to transform them into latitudes and longitudes.

function geocode_Addresses() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var locationInfo = sheet.getRange(1, 1, sheet.getLastRow() - 1, 1).getValues();
  var geoResults, lat, lng;

  for (var i = 0; i < locationInfo.length; i++) {
    geoResults = Maps.newGeocoder().geocode(locationInfo[i]);

    // Get the latitude and longitude
    lat = geoResults.results[0];
    lng = geoResults.results[0].geometry.location.lng;
    sheet.getRange(i+1, 2, 1, 1).setValue(lat + "," + lng);    

Important: The sleep function is important else Google Apps Script might return an error saying Service Invoked Too Many Times.