<

What is GeoCoding, Reverse GeoCoding and how to create a simple C# App?

Published on
5,246 Points
2,146 Views
1 Endorsement
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 the application using Google's GeoCoding/Reverse Geocoding.
This article will teach you what GeoCoding and Reverse Geocoding is and how to write a simple C# console application.
I also added some links, for more detailed information for this topic.

What is Geocoding and Reverse Geocoding?

Geocoding: Is the process when you convert an address into geo-coordinates (Latitude, Longitude).

For example: 

    When you search for “Strada+Tudor+Vladimirescu+34,+Zalău” in GoogleMaps (https://maps.googleapis.com/maps/api/geocode/json?address=Strada+Tudor+Vladimirescu+34,+Zal%C4%83u&key=YOUR_API_KEY&sensor=false), you will get the following coordinates from JSon Geometry/Location:

    47.18998999999999, 23.061813 

Converted to deg/min/sec is:

Latitude: 47 deg 11 min 23.964 sec

Longitude: 23 deg 3 min 42.527 sec

To test GeoCoding without API KEY, there is an example on Google: https://google-developers.appspot.com/maps/documentation/utils/geocoder/

For C# Geocoding sample, check the GeoCoding (string address) function.


Reverse GeoCoding: Is the opposite process, when you convert Geo-coordinates(Latitude, Longitude) to a human readable address.

For example: 

    If you search (https://maps.googleapis.com/maps/api/geocode/json?latlng=47.18998999999999,23.061813&key=YOUR_API_KEY&sensor=false), for a specific coordinate (47.18998999999999, 23.061813) in Google Maps, you will get the following address from JSON formatted_address:

    Strada Tudor Vladimirescu 34, Zalău, Romania

    To test Reverse GeoCoding without API KEY, there is an example on Google: https://google-developers.appspot.com/maps/documentation/utils/geocoder/

For C# Reverse Geocoding sample, check the ReverseGeoCoding(string latitude, string longitude) function.


* More details about how GeoCoding and Reverse GeoCoding works, you can find in the following links:

  1. https://developers.google.com/maps/documentation/geocoding/start
  2. https://en.wikipedia.org/wiki/Geocoding
  3. https://en.wikipedia.org/wiki/Reverse_geocoding


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 GeoCoding and Reverse GeoCoding 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 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

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 GeoResult.cs), this will be used for deserializing the JSON request

This is the final view of my project:

The source code for GeoResult.cs:

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

namespace GeoCoding_Art
{
    public class GoogleGeoCodeResponse
    {

        public string status { get; set; }
        public results[] results { get; set; }

    }

    public class results
    {
        public string formatted_address { get; set; }
        public geometry geometry { get; set; }
        public string[] types { get; set; }
        public address_component[] address_components { get; set; }
    }

    public class geometry
    {
        public string location_type { get; set; }
        public location location { get; set; }
    }

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

    public class address_component
    {
        public string long_name { get; set; }
        public string short_name { get; set; }
        public string[] types { get; set; }
    }
}

The source code for Program.cs:

using Newtonsoft.Json; //added JSON.NET with Nuget
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;

namespace GeoCoding_Art
{
    class Program
    {
        const string apiKey = "YOUR_API_KEY"; //!!!!paste your API KEY HERE!!!!
        static string baseUrlGC = "https://maps.googleapis.com/maps/api/geocode/json?address="; // part1 of the URL for GeoCoding
        static string baseUrlRGC = "https://maps.googleapis.com/maps/api/geocode/json?latlng="; // part1 of the URL for Reverse GeoCoding
        static string plusUrl="&key="+apiKey+"&sensor=false"; // part2 of the URL

        static public int DisplayMenu() // I add a menu for selecting between 1 - GeoCoding / 2 - Reverse Geocoding / 3 - Exit
        {
            Console.WriteLine("GEOCODING TUTORIAL (Select and hit Enter):");
            Console.WriteLine();
            Console.WriteLine("1. GeoCoding"); // 1 for GeoCoding
            Console.WriteLine("2. Reverse GeoCoding"); // 2 for Reverse Geocoding
            Console.WriteLine("3. Exit"); // 3 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 or 2
                {
                    case "1":    //if the input for menu is 1, then call the GeoCoding function
                        Console.WriteLine("===== GEOCODING =====");
                        Console.WriteLine("Enter an address for GeoCoding Result: ");
                        string inputAddress = Console.ReadLine();
                        Console.WriteLine("-------------------------------------");
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("RESULT: " + GeoCoding(inputAddress));
                        Console.ForegroundColor = ConsoleColor.Gray;
                    break;
                    case "2":    //if the input for menu is 2, then call the ReverseGeoCoding function
                        Console.WriteLine("===== REVERSE GEOCODING =====");
                        Console.WriteLine("Enter a Latitude: ");
                        string latitude = Console.ReadLine();
                        Console.WriteLine("Enter a Longitude: ");
                        string longitude = Console.ReadLine();
                        Console.WriteLine("-------------------------------------");
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("RESULT: " + ReverseGeoCoding(latitude,longitude));
                        Console.ForegroundColor = ConsoleColor.Gray;
                    break;
                }
            } while (menuInput != 3); 


        }

        static string GeoCoding(string address)
        {
            var json = new WebClient().DownloadString(baseUrlGC + address.Replace(" ", "+") 
                + plusUrl);//concatenate URL with the input address and downloads the requested resource
            GoogleGeoCodeResponse jsonResult = JsonConvert.DeserializeObject<GoogleGeoCodeResponse>(json); //deserializing the result to GoogleGeoCodeResponse

            string status = jsonResult.status; // get status 

            string geoLocation = String.Empty;

            if (status == "OK") //check if status is OK
            {
                for (int i = 0; i < jsonResult.results.Length; i++) //loop throught the result for lat/lng
                {
                    geoLocation += "Latitude: " + jsonResult.results[i].geometry.location.lat + 
                    " / Longitude: " + jsonResult.results[i].geometry.location.lng + Environment.NewLine; //append the result addresses to every new line
                }
                return geoLocation; //return result
            }
            else 
            {
                return status; //return status / error if not OK
            }
        }

        static string ReverseGeoCoding(string latitude, string longitude)
        {
            var json = new WebClient().DownloadString(baseUrlRGC + latitude.Replace(" ", "") + "," 
                + longitude.Replace(" ", "") + plusUrl);//concatenate URL with the input lat/lng and downloads the requested resource
            GoogleGeoCodeResponse jsonResult = JsonConvert.DeserializeObject<GoogleGeoCodeResponse>(json); //deserializing the result to GoogleGeoCodeResponse

            string status = jsonResult.status; // get status

            string geoLocation = String.Empty;

            if (status == "OK") //check if status is OK
            {
                for (int i = 0; i < jsonResult.results.Length; i++) //loop throught the result for addresses
                {
                    geoLocation += "Address: " + jsonResult.results[i].formatted_address + Environment.NewLine; //append the result addresses to every new line
                }
                return geoLocation; //return result
            }
            else 
            {
                return status; //return status / error if not OK
            }
        }
    }
}



Some screenshots of the working app

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


1 - GeoCoding (searched term: Strada Tudor Vladimiresc 34, Zalau, the result is with red):



2 - Reverse GeoCoding (searched term: Latitude: 47.18998999999999 / Longitude: 23.061813, the result is with red):


3 - for Exit 


Source Code

GeoResult.cs

Program.cs


Entire Project

GeoCoding_Art2.zip



I wish you happy coding! 


Molnar Istvan



1
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