<

How Google Elevation works and how to create a simple C# App?

Published on
3,605 Points
605 Views
Last Modified:
Editors:
Molnár István
People must help one another; it's nature's law. — JEAN DE l.A FONTAINE
The article's main focus is , to create a C# console application using Google's Elevation API.
For more detailed information about this topic, use the attached links.

What is Google Elevation ?


Elevation is the height above or below a fixed reference point. The elevation is the referring to points on the Earth's surface. 


We also use the following two terms:

    - altitude: points above the surface

    - depth: points below the surface


For example:


1. Simple elevation (one pair of coordinate - lat/lng)


If you search (https://maps.googleapis.com/maps/api/elevation/json?locations=47.18998999999999,23.061813&key=YOUR_API_KEY), for a specific coordinate (47.18998999999999, 23.061813) in Google Maps, you will get the following elevation result from JSON :

 

    elevation:    254.4218444824219

 

To test the Elevation without API KEY, there is an example on Google: https://developers.google.com/maps/documentation/javascript/examples/elevation-simple


    For C# Elevation sample, check the Elevation(string latitudeE, string longitudeE) function.



2. Multiple elevations (multiple pairs of coordinates - lat/lng)

  

You can also request multiple elevation results, just by adding multiple pair of coordinates and separated by the PIPE character "|". If you request https://maps.googleapis.com/maps/api/elevation/json?locations=47.18998999999999,23.061813|47.16998999999999,23.061813&key=YOUR_API_KEY , you will get the following elevation results:


//the elevation result for the first pair of coordinates

elevation:    254.4218444824219
lat:    47.18998999999999
lng:    23.061813


//the elevation result for the second pair of coordinates
elevation:    294.3569030761719
lat:    47.16998999999999
lng:    23.061813


For C# MultipleElevation sample, check the MultipleElevation(string multiplecoords) function.  (It asks the user for coordinates, until the input values are empty - when the Enter key is pressed for both of the coordinates - lat/lng)



3. Path elevations (multiple pairs of coordinates - lat/lng and number of samples)    


Another great feature is that you can requests elevation data along a straight line (path). For example starting from point A to point B, specifying the number of samples. 

    You can ask for example 3 samples:

    - 2x Endpoints

    - 1x Half-point


    If you search for: https://maps.googleapis.com/maps/api/elevation/json?path=47.18998999999999,23.061813|47.16998999999999,23.0618131&samples=3&key=YOUR_API_KEY, you will get the following from the JSon results:


//sample 1 - Endpoint

elevation    254.4218444824219    
lat    47.18998999999999
lng    23.061813


//sample 2 - Half-point
elevation    288.4825134277344
lat    47.17998999999999
lng    23.06181305000942


//sample 3 - Endpoint
elevation    294.3571472167969
lat    47.16998999999999
lng    23.0618131


For C# PathElevation sample, check the PathElevation(string multiplecoords, string nrofsamples) function.  (It asks the user for coordinates until the input values are empty - when Enter key is pressed for both of the coordinates - lat/lng, after that it asks for the number of samples)


 * More details about how Elevation works and how we use it, you can find in the following links:

    - Elevation Wiki

    - Google Elevation


C# Source Code sample:

The following source code is written in C# Console Application (Framework 4.5). To save space, I created a single project for Simple Elevation, Multiple Elevations, Path Elevations and a class for deserializing the JSON.

 

To run it, you will need the following:

 

-create a new API Key 

 

-enable Maps Javascript API


-enable Maps Elevation API

 

-enable GeoLocation API

 

-enable GeoCoding API

 

-Visual Studio

 

Tip: don't forget to enable billing information in Google for the API and attach to the project

 

In this article I will not cover, how to enable API Keys on Google, but you can find more information on their site:

 

https://developers.google.com/maps/documentation/javascript/get-api-key

 

Create a new Console application project and after that, from NuGet, install JSon.Net (Newtonsoft.Json):

- Step 1 - File->New-> Project  (I used .Net Framework 4.5)



- Step 2 - Install from Nuget Json.Net:





- Step 3 - Create a New class in the project (I named it ElevResult.cs), this will be used for deserializing the JSON request.


This is the final view of my project:


The source code for ElevResult.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Elevation_Art
{
    public class GoogleElevCodeResponse
    {
        public string status { get; set; }
        public resultsElev[] results { get; set; }
    }

    public class resultsElev
    {
        public string elevation { get; set; }
        public locationElev location { get; set; }
        public string resolution { get; set; }
    }

    public class locationElev
    {
        public string lat { get; set; }
        public string lng { get; set; }
    }
}

The source code for Program.cs:

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace Elevation_Art
{
    class Program
    {
        const string apiKey = "YOUR_API_KEY"; //!!!!paste your API KEY HERE!!!! 
        static string baseUrlEL = "https://maps.googleapis.com/maps/api/elevation/json?locations="; // part of the URL for Elevation
        static string baseUrlELP = "https://maps.googleapis.com/maps/api/elevation/json?path="; // part of the URL for Elevation
        static string plusUrl = "&key=" + apiKey + "&sensor=false"; // part2 of the URL

        static public int DisplayMenu() // I add a menu for selecting between 1 - Elevation / 2 - Elevation with Multiple Coordinates / 3 - PathElevation with Multiple Coordinates / 4 - Exit
        {
            Console.WriteLine();
            Console.WriteLine("ELEVATION TUTORIAL (Select and hit Enter):");
            Console.WriteLine();
            Console.WriteLine("1. Elevation"); // 1 Elevation with single pair of coordinates
            Console.WriteLine("2. Elevation with Multiple Coordinates"); // 2 Multiple Elevation results, from multiple pair of coordinates
            Console.WriteLine("3. PathElevation with Multiple Coordinates"); // 3 Multiple Elevation (PathElevation) results, from multiple pair of coordinates and samples
            Console.WriteLine("4. Exit"); // 4 Exit
            Console.WriteLine();
            var result = Console.ReadLine(); //waiting for an integer input for the menu; value can between 1-3
            return Convert.ToInt32(result); //converting result to an integer for the menu
        }

        static void Main(string[] args)
        {
            int menuInput = 0;
            do // do-while statement for the menu, it loops until the input is 3 (Exit) 
            {
                Console.ForegroundColor = ConsoleColor.Green; // changing color for the console to green 
                menuInput = DisplayMenu(); //getting the result of the input for the menu
                Console.ForegroundColor = ConsoleColor.Gray; // changing to default color

                switch (menuInput.ToString()) //switch statement for checking if input is 1 - 3, 4 - Exit
                {
                    case "1":    //if the input for menu is 1, then call the Elevation function
                        Console.WriteLine("===== ELEVATION =====");
                        Console.WriteLine("Enter a Latitude: ");
                        string latitudeE = Console.ReadLine();
                        Console.WriteLine("Enter a Longitude: ");
                        string longitudeE = Console.ReadLine();
                        Console.WriteLine("-------------------------------------");
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("RESULT: " + Elevation(latitudeE, longitudeE) + " meters");
                        Console.ForegroundColor = ConsoleColor.Gray;
                        break;
                    case "2":    //if the input for menu is 2, then call the MultipleElevation function
                        Console.WriteLine("===== MULTIPLE ELEVATION =====");
                        string latitudeEM = string.Empty;
                        string longitudeEM = string.Empty;
                        StringBuilder sb = new StringBuilder();
                        do
                        {
                            Console.WriteLine("Enter a Latitude: ");
                            latitudeEM = Console.ReadLine();
                            Console.WriteLine("Enter a Longitude: ");
                            longitudeEM = Console.ReadLine();

                            sb.Append(latitudeEM + "," + longitudeEM + "|"); //format LAT/LNG coordinates and append to StringBuilder 
                        } while ((latitudeEM.ToString() != "") || (longitudeEM.ToString() != "")); //request input from user, util LAT and LNG is empty char (Enter)
                        Console.WriteLine("-------------------------------------");
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("RESULT: " + MultipleElevation(sb.ToString().Replace("|,|", "")) + " meters"); //call the function MultipleElevation 
                        Console.ForegroundColor = ConsoleColor.Gray;
                        break;
                    case "3":    //if the input for menu is 3, then call the PathElevation function
                        Console.WriteLine("===== PATH ELEVATION =====");
                        string latitudeEMP = string.Empty;
                        string longitudeEMP = string.Empty;
                        StringBuilder sbp = new StringBuilder();
                        do
                        {
                            Console.WriteLine("Enter a Latitude: ");
                            latitudeEMP = Console.ReadLine();
                            Console.WriteLine("Enter a Longitude: ");
                            longitudeEMP = Console.ReadLine();

                            sbp.Append(latitudeEMP + "," + longitudeEMP + "|"); //format LAT/LNG coordinates and append to StringBuilder 
                        } while ((latitudeEMP.ToString() != "") || (longitudeEMP.ToString() != "")); //request input from user, util LAT and LNG is empty char (Enter)

                        Console.WriteLine("Enter the number of samples: ");
                        string nrOfSamples = Console.ReadLine();

                        Console.WriteLine("-------------------------------------");
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("RESULT: " + PathElevation(sbp.ToString().Replace("|,|", ""),nrOfSamples) + " meters"); //call the function PathElevation
                        Console.ForegroundColor = ConsoleColor.Gray;
                        break;
                }
            } while (menuInput != 4);


        }

        private static string Elevation(string latitudeE, string longitudeE)
        {
            var json = new WebClient().DownloadString(baseUrlEL + latitudeE.Replace(" ", "") + ","
                + longitudeE.Replace(" ", "") + plusUrl);//concatenate URL with the input lat/lng and downloads the requested resource
            GoogleElevCodeResponse jsonResult = JsonConvert.DeserializeObject<GoogleElevCodeResponse>(json); //deserializing the result to GoogleElevCodeResponse

            string status = jsonResult.status; // get status

            string geoElevation = String.Empty;
            geoElevation += Environment.NewLine;

            if (status == "OK") //check if status is OK
            {
                for (int i = 0; i < jsonResult.results.Length; i++) //loop throught the result for addresses
                {
                    geoElevation += "Lat/Lng[" + i + "]: " + jsonResult.results[i].location.lat + " / " + jsonResult.results[i].location.lng + " Elevation[" + i + "]: " + jsonResult.results[i].elevation + Environment.NewLine; //append the result elevations and coords to every new line
                }
                return geoElevation; //return result
            }
            else
            {
                return status; //return status / error if not OK
            }

        }

        private static string MultipleElevation(string multiplecoords)
        {
            var json = new WebClient().DownloadString(baseUrlEL + multiplecoords + plusUrl);//concatenate URL with the input lat/lng and downloads the requested resource
            GoogleElevCodeResponse jsonResult = JsonConvert.DeserializeObject<GoogleElevCodeResponse>(json); //deserializing the result to GoogleElevCodeResponse

            string status = jsonResult.status; // get status

            string geoElevation = String.Empty;
            geoElevation += Environment.NewLine;

            if (status == "OK") //check if status is OK
            {
                for (int i = 0; i < jsonResult.results.Length; i++) //loop throught the result for addresses
                {
                    geoElevation += "Lat/Lng[" + i + "]: " + jsonResult.results[i].location.lat + " / " + jsonResult.results[i].location.lng + " Elevation[" + i + "]: " + jsonResult.results[i].elevation + Environment.NewLine; //append the result elevations and coords to every new line
                }
                return geoElevation; //return result
            }
            else
            {
                return status; //return status / error if not OK
            }

        }

        private static string PathElevation(string multiplecoords, string nrofsamples)
        {
            var json = new WebClient().DownloadString(baseUrlELP + multiplecoords+"&samples="+nrofsamples+ plusUrl);//concatenate URL with the input lat/lng and downloads the requested resource
            GoogleElevCodeResponse jsonResult = JsonConvert.DeserializeObject<GoogleElevCodeResponse>(json); //deserializing the result to GoogleElevCodeResponse

            string status = jsonResult.status; // get status

            string geoElevation = String.Empty;
            geoElevation += Environment.NewLine;

            if (status == "OK") //check if status is OK
            {
                for (int i = 0; i < jsonResult.results.Length; i++) //loop throught the result for addresses
                {
                    geoElevation += "Lat/Lng[" + i + "]: " + jsonResult.results[i].location.lat + " / " + jsonResult.results[i].location.lng + " Elevation[" + i + "]: " + jsonResult.results[i].elevation + Environment.NewLine; //append the result elevations and coords to every new line
                }
                return geoElevation; //return result
            }
            else
            {
                return status; //return status / error if not OK
            }

        }

    }
}

Some screenshots of the working app



The menu: (Waiting for user input 1-4)



1. Simple Elevation (for the following coords: 47.18998999999999, 23.061813, check result in red):



2. Multiple Elevations (for the following coords: 47.18998999999999,23.061813|47.16998999999999,23.061813, check results in red):



3. PathElevations (for the following coords: 47.18998999999999,23.061813|47.16998999999999,23.061813 and with the number of samples: 3, check results in red):



4. for Exit 


Source Code:



ElevResult.cs

Program.cs



Entire Project:



Elevation_Art2.zip



I wish you happy coding! 


Molnár István



0
Ask questions about what you read
If you have a question about something within an article, you can receive help directly from the article author. Experts Exchange article authors are available to answer questions and further the discussion.
Get 7 days free