Click here to Skip to main content
15,891,184 members
Articles / Web Development / ASP.NET
Tip/Trick

Finding Co-ordinates of an Address in ASP.NET C#

Rate me:
Please Sign up or sign in to vote.
4.75/5 (6 votes)
7 Sep 2013CPOL1 min read 37.6K   10   3
It's a GeoCoding technique

Introduction

In this tip, we shall see how to find the co-ordinates (Longitude/ Latitude) of a given address. This technique is called Geocoding. We can do the opposite of the same (finding address from co-ordinates) but in this tip, we shall be specific to geocoding only. We will use an API of Google Maps for this purpose. Google Maps API return the XML or JSON. It depends on us as to what we want to use. In the following code, we use XML.

Background

There are so many tutorials available to use geocoding. I found this necessary to update the information of users as the use of this API is changed a bit. And the following code is very simple to understand. We shall be specific to find just the co-ordinates. You need Visual Studio 2010/2012 for this.

Using the Code

Let's start!

Open Visual Studio and create a new project and create an ASP.NET web application with C# and name the project as "Co-Ordinates".

Now add a new web form in the solution and let the name as default as WebForm1.aspx and add the following code in WebForm1.aspx file.

ASP.NET
<p>Your Address Here : </p><asp:TextBox runat="server" ID="txtAddress"></asp:TextBox>
      <asp:Button runat="server" ID="btnGetCoordinates"
      Text="Get Coordinates" OnClick="btnGetCoordinates_Click" />

      <p>This is the Lattitude of Address</p>&nbsp&nbsp
      <asp:Label ID="lblLattitude" runat="server"></asp:Label><br />

      <p>This is the Longtitude of Address</p>&nbsp&nbsp
      <asp:Label ID="lblLongtitude" runat="server">
      </asp:Label>
C#
// Now add the following Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.IO;
using System.Xml;
using System.Net;
using System.Text;

namespace Co_Ordinates
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            
        }

        protected void btnGetCoordinates_Click(object sender, EventArgs e)
        {
            Adress adrs = new Adress();
            adrs.Address = txtAddress.Text.ToString();
            adrs.GeoCode();
            lblLattitude.Text = adrs.Latitude;
            lblLongtitude.Text = adrs.Longitude;
        }
    }

    public class Adress
    {
        public Adress()
        { 
        }
        //Properties
        public string Latitude { get; set; }
        public string Longitude { get; set; }
        public string Address { get; set; }

        //The Geocoding here i.e getting the latt/long of address
        public void GeoCode()
        {
            //to Read the Stream
            StreamReader sr = null;
            
            //The Google Maps API Either return JSON or XML. We are using XML Here
            //Saving the url of the Google API 
            string url = String.Format("http://maps.googleapis.com/maps/api/geocode/xml?address=" + 
            this.Address + "&sensor=false");
            
            //to Send the request to Web Client 
            WebClient wc = new WebClient();
            try
            {
                sr = new StreamReader(wc.OpenRead(url));
            }
            catch (Exception ex)
            {
                throw new Exception("The Error Occured"+ ex.Message);
            }

            try
            {                
                XmlTextReader xmlReader = new XmlTextReader(sr);
                bool latread = false;
                bool longread = false;

                while (xmlReader.Read())
                {
                    xmlReader.MoveToElement();
                        switch (xmlReader.Name)
                        {
                            case "lat":

                                if (!latread)
                                {
                                    xmlReader.Read();
                                    this.Latitude = xmlReader.Value.ToString();
                                    latread = true;
                                    
                                }
                                break;
                            case "lng":
                                if (!longread)
                                {
                                    xmlReader.Read();
                                    this.Longitude = xmlReader.Value.ToString();
                                    longread = true;
                                }
                            
                                break;
                        }   
                }
            }
            catch (Exception ex)
            {
                throw new Exception("An Error Occured"+ ex.Message);
            }
        }
    }
}

Points of Interest

The result will be the simple longitude and latitude of the address. And remember to give the address in proper format as you give in Google maps to find an address.

History

This is the second version of my previous blog. Some changes have been made.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Pakistan Pakistan
I am a Software Engineer. I love Programming Smile | :)

Comments and Discussions

 
QuestionResponse from URL, What mistake i have in this code? Pin
Hassan_Mirza12-May-19 7:49
Hassan_Mirza12-May-19 7:49 
GeneralMy vote of 5 Pin
Аslam Iqbal8-Sep-13 1:53
professionalАslam Iqbal8-Sep-13 1:53 
nice thinking
GeneralRe: My vote of 5 Pin
Saqib Mobeen8-Sep-13 3:54
Saqib Mobeen8-Sep-13 3:54 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.