Chris Mendez in For Developers, Javascript, NodeJS, Telematics

NodeJS: Return Elevation from Google Maps API

Here's how to use Google Maps API to get the elevation of a specific location.

/**
Use Google maps API to return the elevation of a given [ lat, lng ]  
**/

var http = require("http"),  
sys  = require("util");

//Google provides the elevation of a given latitude + longitude
function getElevation( lat, lng, callback ){  
  //Google Maps Options
  var options = {
    host: "maps.googleapis.com",
    port: 80,
    path: "/maps/api/elevation/json?locations=" + lat + "," + lng + "&sensor=true"
  };
  //GET request that handles the parsing of data too
  http.get( options, function( res ){
    var data = "";

    res.on( "data", onData );
    function onData( chunk ){
      data += chunk;  
    }

    res.on( "end", onEnd );
    function onEnd( chunk ){
      var el_response = JSON.parse( data );
      callback( el_response.results[0].elevation );
    }    
  });
}

/*******************************
Event Handlers  
*******************************/
//Run the Requests sequentially
var elevations = [];  
function elevationResponse( elevation ){  
  elevations.push( elevation );
  if( elevations.length == 2 ){
    console.log( "Elevations: " + elevations );
  }
}

getElevation( 40.714728, -73.998672, elevationResponse );  
getElevation( -40.714728, 73.998672, elevationResponse );