Categories
Code

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: labnol.org

  var origin = "10 Hanover Square, NY 10005";
  var destination = "Times Square";
  var travelMode = Maps.DirectionFinder.Mode.WALKING;
  
  var directions = Maps.newDirectionFinder()
  .setOrigin(origin)
  .setDestination(destination)
  .setMode(travelMode)
  .getDirections();
  
  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 = route.steps.map(function(step) {
    return step.html_instructions.replace(/<[^>]+>/g, "")
  }).join("\n");
  
  Logger.log(steps);

}
Categories
Code

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 "https://maps.google.com/maps?q="+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;
        longLat.lat = l.lat;
        return longLat;
      }
    }
    else {
      return "error";
    }
}
 
Categories
Code

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 = "http://my.ctrlq.org/maps/#" + 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 = pos.lat();
        lng = pos.lng();
    }

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

    generateURL(parameters);

}

function updateMap() {

    var center = map.getCenter();
    generateURL(map.getMapTypeId() + "|" + map.getZoom() + "|" + center.lat() + "|" + 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');
    map.controls[google.maps.ControlPosition.TOP_LEFT].push(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) {
            return;
        }

        if (place.geometry.viewport) {
            map.fitBounds(place.geometry.viewport);
        } else {
            map.setCenter(place.geometry.location);
            map.setZoom(17);
        }

    });

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

}

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

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: http://webapps.stackexchange.com/questions/16757 */
function getDirection(city1, city2) {

 var directions = Maps.newDirectionFinder()
    .setOrigin(city1).setDestination(city2)
    .setMode(Maps.DirectionFinder.Mode.DRIVING)
    .getDirections();
 
 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": result.lat} 
}

function getDistance(c1, c2, opt) {
  var lat1 = rad(c1.lat), lat2 = rad(c2.lat);
  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;
}
Categories
Code

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) {
        event.preventDefault();
        $(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);
            geocoder.geocode({
                '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") {
                        $('#zipcode').html(address.long_name);
                        $('#location').html(results[0].formatted_address);
                        $('#showMyLocation').hide();
                    }
                }
            });
        });
        return false;
    });
});
Categories
Code

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: "
Drag this pin anywhere on the Google Map to know the approximate address of that point.
" }); 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( "
" + responses[0].formatted_address + "
" + "Latitude: " + marker.getPosition().lat() + "
" + "Longitude: " + marker.getPosition().lng() + "
" ); 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."); } }); } }
Categories
Code

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].geometry.location.lat;
    lng = geoResults.results[0].geometry.location.lng;
    sheet.getRange(i+1, 2, 1, 1).setValue(lat + "," + lng);    
    Utilities.sleep(1000);    
  }
}

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