Featured Posts

Autocomplete using Html, JSON, MVC, jQuery I found an awesome AutoComplete tutorial (here: http://www.nodstrum.com/2007/09/19/autocompleter/#comment) using PHP, jQuery, MySQL, and decided to port it over to Microsoft's ASP.NET MVC. Turned out...

Readmore

ASP.NET MVC sample application Below is a fully functional asp.net mvc sample application project. Go ahead a download it, play with it, make suggestions, extend, etc. If you have any suggestions for improvements, just drop me a line...

Readmore

Using nHibernate, Castle ActiveRecord, and ASP.NET... So this is my first post, with that this blog's objective: to post all the code shortcuts, how-to's, tips-tricks, etc. so they are handy whenever I need them. It always seems that at some point I need...

Readmore

How to add or delete a row to a html table using jQuery,... This post covers a piece of functionality I'm always using, and just wanted a spot where I can do some quick copy/paste. There are a few pieces of functionality needed to make this happen, and the technology...

Readmore

Dual listboxes in jquery Ok, so this one should be simple, more for reference. The goal is to create a dual list box using jQuery and MVC. To accomplish this, we are going to use the "appendTo" manipulation (http://docs.jquery.com/Manipulation)....

Readmore

  • Prev
  • Next

Latitude and Longitude Lookup with jQuery, C#, ASP.NET MVC

Posted on : 18-02-2010 | By : bill sternberger | In : ASP.NET MVC, C#, jquery

Tags: ,

12

I recently had a requirement for a mapping application that required me to pass in longitude and latitude coordinates. It wasn’t realistic to have the user look those values up, so I had to figure out a way to automatically lookup the coordinates given a zip code.

There are tons of pay services (some of which I use), but for this project needed something free. I stumbled on http://www.geonames.org/ which has a great service. You can see their webservice documentation here: http://www.geonames.org/export/web-services.html.

Ok, let’s get started:

Web form

These are the input fields we will use to perform the lookup. We are going to have three textboxes, one which has an onchange event.

    Zip Code<br/>
    <%= Html.TextBox("Zip", "", new { @onchange = "LookupCoordinates(this.value)" })%>
    <br/><br/>
    Latitude: <%= Html.TextBox("Lat") %>,
    Longitude:<%= Html.TextBox("Lon") %>

jQuery Function

This function is responsible for looking up the latitude and longitude coordinates, and populating the results into the textboxes. Note that I’m wiring in US as the country below. The country is an optional parameter, when entered gives you more relevant results. Otherwise you are going to have to write some kind of loop.

    function LookupCoordinates(zip) {
            $.post("/Home/LookupCoordinates",
            { Zip: zip, Country: "US" },
            function(data) {
                var result = eval('(' + data + ')');
                var coordinates = result.split(",");
                $("#Lat").val(coordinates[0]);
                $("#Lon").val(coordinates[1]);
            });
        }

Call Geonames.org

In this sample, the call to geonames.org is wired into the controller. In real life, you probably want to wrap it in some kind of helper or service class. There are a few using statements you will need:

using System.IO;
using System.Net;
using System.Xml;

The above namespaces are important because we are going to make a WebRequest, and then parse the Xml results. The webservice method we are going to call is:

http://ws.geonames.org/postalCodeSearch?postalcode=78702&maxRows=10&country=US

Since we know the Zip and the Country, we should in theory only get 1 result. Below is a screenshot of the elements returned for our 78702 search (Austin):

Onto the method:

    public ActionResult LookupCoordinates(string Zip, string Country)
    {
        string Lat = "";
        string Lon = "";
        string PostUrl = "http://ws.geonames.org/postalCodeSearch?postalcode=" + Zip + "&maxRows=10&country=" + Country;
        WebResponse webResponse = webRequest.GetResponse();
        if (webResponse == null)
        { }
        else
        {
            StreamReader sr = new StreamReader(webResponse.GetResponseStream());
            string Result = sr.ReadToEnd().Trim();
            if (Result != "")
            {
                // Load the response into an XML doc
                XmlDocument xdoc = new XmlDocument();
                xdoc.LoadXml(Result);
                //  Navigate to latitude node
                XmlNodeList name = xdoc.GetElementsByTagName("lat");
                if (name.Count > 0)
                {
                    Lat = name[0].InnerText;
                }
                //  Navigate to longitude node
                name = xdoc.GetElementsByTagName("lng");
                if (name.Count > 0)
                {
                     Lon = name[0].InnerText;
                }
            }
        }
        return Json(Lat + "," + Lon);
    }

From there, the method returns the latitude and longitude in a comma separated string, the javascript call splits the results and populates each respective text box. Below is a video preview – really short, really lame, but you get to see the code in action:

Comments (12)

[...] Latitude and Longitude Lookup with jQuery, C#, ASP.NET MVC [...]

[...] coordinates, but it took a while to figure out how to find them! It would be nice if you could …Latitude and Longitude Lookup with jQuery, C#, ASP.NET MVCI recently had a requirement for a mapping application that required me to pass in longitude and [...]

Thanks for sharing this nice info.

Very nice, would this same script work with PHP?

@Eric – You could run it from PHP, you would need to have a method in PHP to handle LookupCoordinates(string Zip, string Country), which is just a post that can be done w/curl, and then parse the xml response.

Hi,

This code is giving error in my website.

Please give me more detail .

I shall be heighly thankfull .

Thanks

Shatrughan

Just one question. Why call my own server, which in term calls the Geonames.org server? Why not directly call the Geonames.org server? Saves you a request to handle.

@Eric Will this return lat and long for India?

@Bill Sternberger Will this return lat and long for India?

Depending upon which service you use, it will return for *most* of India. Every now and then there are certain areas it can’t find, but I’ve had decent results. I started subscribing to this service: http://www.geoipapi.com/, they have been great.

You could do that! For my apps I wrap the functionality in a class for parsing/storing/error handling, and I’ve evolved to having multiple services in case one doesn’t return results, the code will check the others.

Do you have any of your sample code?

Write a comment