Computer Magic Logo
Get the elevation of a point

Friday, December 2, 2016

Published by Aristotelis Pitaridis

The google maps elevation service allow us to find the elevation for one or more coordinates. The following example demonstrates how to find the elevation for clicked location on the map.

<!DOCTYPE html>
<html>
<head>
    <style>
        #map {
            height: 400px;
            width: 600px;
        }
    </style>
</head>
<body>
    <h3>My Google Maps Demo</h3>
    <div id="map"></div>
    <script>
        function initMap() {
            var elevator = new google.maps.ElevationService();
            var location = { lat: 35.339186, lng: 25.1315903 };
            var map = new google.maps.Map(document.getElementById('map'), {
                zoom: 12,
                center: location
            });

            google.maps.event.addListener(map, 'click', function (event) {
                getElevation(elevator, event.latLng);

            });
        }

        function getElevation(elevator, clickedLocation) {
            // Create a LocationElevationRequest object using the array's one value
            var positionalRequest = { 'locations': [clickedLocation] };

            // Initiate the location request
            elevator.getElevationForLocations(positionalRequest, function (results, status) {
                if (status == google.maps.ElevationStatus.OK) {
                    // Retrieve the first result
                    if (results[0]) {
                        console.log("Last point clicked : " + results[0].elevation.toFixed(3) + " m / " + (results[0].elevation * 3.2808399).toFixed(3) + " feet");
                    }
                    else {
                        outputDiv.innerHTML = "No results found";
                    }
                }
                else {
                    outputDiv.innerHTML = "Elevation service failed due to: " + status;
                }
            });
        }

    </script>
    <script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"></script>
</body>
</html>