Showing elevation along a path
by Wolf
HTML
<div>
<div id="map" style="height:500px;"></div>
<div id="elevation_chart"></div>
</div>
<script src="https://www.google.com/jsapi"></script>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">
</script>
CSS
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
JavaScript
// Load the Visualization API and the columnchart package.
google.load('visualization', '1', {packages: ['columnchart']});
function initMap() {
// The following path marks a path from Mt. Whitney, the highest point in the
// continental United States to Badwater, Death Valley, the lowest point.
var path = [
{lat: 0, lng: 0}, // Null island
{lat: -1.114052, lng: 33.004641}, // Lake victoria
{lat: 19.034594, lng: 39.987424}, // Red Sea
{lat: 40.790835, lng: 51.586902}, // Caspian Sea
{lat: 47.121984, lng: 9.216727}, // Walensee
{lat: 61.313131, lng: 28.130265}]; // Saimaa
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 2,
center: path[1],
mapTypeId: 'terrain'
});
// Create an ElevationService.
var elevator = new google.maps.ElevationService;
// Draw the path, using the Visualization API and the Elevation service.
displayPathElevation(path, elevator, map);
}
function displayPathElevation(path, elevator, map) {
// Display a polyline of the elevation path.
new google.maps.Polyline({
path: path,
strokeColor: '#0000CC',
strokeOpacity: 0.4,
map: map
});
// Create a PathElevationRequest object using this array.
// Ask for 256 samples along that path.
// Initiate the path request.
elevator.getElevationAlongPath({
'path': path,
'samples': 256
}, plotElevation);
}
// Takes an array of ElevationResult objects, draws the path on the map
// and plots the elevation profile on a Visualization API ColumnChart.
function plotElevation(elevations, status) {
var chartDiv = document.getElementById('elevation_chart');
if (status !== 'OK') {
// Show the error code inside the chartDiv.
chartDiv.innerHTML = 'Cannot show elevation: request failed because ' +
status;
return;
}
// Create a new chart in the elevation_chart DIV.
var chart = new google.visualization.ColumnChart(chartDiv);
// Extract the data from which to...