Home > Asp.Net, C# > Yahoo Geocoding API Service in Asp.Net 3.5 C# using WebClient class (Asynchronously)

Yahoo Geocoding API Service in Asp.Net 3.5 C# using WebClient class (Asynchronously)


In this article I am going to explain how to consume yahoo Geocoding API service in Asp.Net C# using web client Asynchronous method.
If you are working with maps you may require latitude and longitude to show the address in map. Yahoo!s APIs is the awesome tool provides APIs for many of the services Maps, Music, Search, Search Marketing, Shopping, Travel etc…

Click here to download the entire article

Assume you have a list of locations in your database and need to pull Geo-coder (latitude and longitude) from yahoo API service  in Asynchronous manner.. (per day you can query 5000 request from a single ip address). Geocoding service is a free service you have to register in order to use it. http://developer.yahoo.com/maps/rest/V1/geocode.html

So lets create a simple class called Location with two properties LocationId,Address.

public class Location
{
public int LocationId { get; set; }
public string Address { get; set; }

public static List<Location> GetLocationList()
{
List<Location> oAddressList = new List<Location>
{
new Location{ LocationId = 1, Address = "1001 Emerald Heights Ct, Reston VA 20191"},
new Location{ LocationId = 2, Address = "1001 University Ave, West Des Moines, IA 50266"},
new Location{ LocationId = 3, Address = "701 First Ave Sunnyvale,CA"},
};
return oAddressList;
}
}

I have hard coded three different addresses you can change this with your database logic.  The next step is to create a new aspx page and make sure if you are using asynchronous call you have to add Async=”true” in the page header of the Aspx page.

Task List in the aspx page.

1) Add Async=”true”  in the page header.
2)
Get the locations list from the business object / database.
3) Initializing yahoo application id (http://developer.yahoo.com/maps/rest/V1/geocode.html).
4) Construct url for geocode service (make sure you are sending address in encode format using Server.UrlEncode method).
4) Consume Geo-code service using web client class with Asynchronous manner.
5) Send Address information along with a custom token, AddressId (so that I can update geocode information to database for the particular address).
5) Download result xml from yahoo api service.
6) Parse the xml content and get Latitude and longitude

In the Page_Load Method

protected void Page_Load(object sender, EventArgs e)
 {
string YAHOO_API_SIGNATURE = "YD-9G7bey8_JXxQP6rxl.fBFGgCdNjoDMACQA--";

 string YAHOO_API_URL = "http://local.yahooapis.com/MapsService/V1/geocode?appid=" + YAHOO_API_SIGNATURE + "&street=";

 string url = string.Empty;

 var oGeoCoderList = Location.GetLocationList();

 foreach (Location location in oGeoCoderList)
 {
 WebClient oWebClient = new WebClient();

 oWebClient.DownloadDataCompleted += new DownloadDataCompletedEventHandler(DownloadDataCompleted);

 url = string.Concat(YAHOO_API_URL, Server.UrlEncode(location.Address));

 oWebClient.DownloadDataAsync(new Uri(url), location.LocationId);
 }
}

Code Explanations

Initializing yahoo application id

string YAHOO_API_SIGNATURE = “YD-9G7bey8_JXxQP6rxl.fBFGgCdNjoDMACQA–”;

Initializing yahoo web service API URL.

string YAHOO_API_URL = “http://local.yahooapis.com/MapsService/V1/geocode?appid=&#8221; + YAHOO_API_SIGNATURE + “&street=”;

Get location list from business object or database.

var oGeoCoderList = Location.GetLocationList();

Create a webclient object

WebClient oWebClient = new WebClient();

Create event handler (DownloadDataCompleted) this event get fired when an asynchronous data download operation complete.

oWebClient.DownloadDataCompleted += new DownloadDataCompletedEventHandler(DownloadDataCompleted);

Append location address with yahoo api url.

url = string.Concat(YAHOO_API_URL, Server.UrlEncode(location.Address));

DownloadDataAsync method downloads resources as System byte array.

oWebClient.DownloadDataAsync(new Uri(url), location.LocationId);

Loop through the location list and send address information to yahoo service along with a custom token, AddressId (so that I can update laster to database for the particular address).

 void DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
 {
 try
 {
 if (e.Error == null) //make sure there is no error.
 {
 byte[] byteContent = e.Result;

 string result = System.Text.Encoding.ASCII.GetString(byteContent);

 if (!string.IsNullOrEmpty(result))
 {
 int addressId = (int)e.UserState;

 var xml = XElement.Parse(result);

 xml = StripXMLNameSpace(xml);

 if (xml != null)
 {
 XElement xelement = (XElement)xml;
 string latitude = (from geoCodeService in xelement.Descendants("Result").Descendants("Latitude")
 select geoCodeService.Value).Take(1).SingleOrDefault<String>();

 string longtitue = (from geoCodeService in xelement.Descendants("Result").Descendants("Longitude")
 select geoCodeService.Value).Take(1).SingleOrDefault<String>();

 UpdateLocation(addressId, latitude, longtitue);
 }
 }
 }
 else
 {
 //log your error information here.
 }
 }
 catch (Exception exp)
 {
 //log system exception here
 }
 }

 void UpdateLocation(int addressId, string latitude, string longtitue)
 {
 //implement your update logic here....
 }

 XElement StripXMLNameSpace(XElement root)
 {
 return new XElement(
 root.Name.LocalName,
 root.HasElements ?
 root.Elements().Select(el => StripXMLNameSpace(el)) :
 (object)root.Value
 );
 }

Once we retrieve the information from yahoo service the above method will convert the result system byte array to string using System.Text.Encoding.ASCII.GetString method and also get the user defined object which we already passed to the method and remove the xmlns:name space  from the XML result and getting the values of latitude and longitude from the nodes. In my upcoming articles  I would like to explain how to integrate Google (MAPS & Street View) and Virtual Earth (with multiple address location)

Hope this help and If you have any comments, please feel free to write your feedback.

You can download the entire article from here or copy paste this URL

http://www.4shared.com/file/241083617/7919b1a7/YahooApiGeoCoder.html

Thanks
Deepu

About these ads
  1. Tim
    April 23, 2010 at 6:13 pm | #1

    Thanks for the article it’s exactly what I was looking for. I downloaded the example and got it working, but I’m having a problem adapting it to my application.

    User enters address data and clicks a button. I moved the page load code to a method and call it from the button click method to get the lat and long from the yahoo service, this all works fine. The problem I have is that I need to do some more processing after I get the lat & long. The DownloadDataCompleted event doesn’t fire until the very end of the button click method, which for me is to late. I need to pass the lat and long to a stored procedure to find locations within a radius and then map them.

    Is there a way to get the DownloadDataCompleted event to fire right after oWebClient.DownloadDataAsync(new Uri(url), 1); ?

    Thanks for your help.

    • April 24, 2010 at 1:48 am | #2

      DownloadDataCompleted event will get fired once the request finishes. I think you are passing one request to yahoo service at a time, is that correct ? If it is that case I guess you do not need Asynchronous call.
      You can simply use some thing like below

      WebClient myWebClient = new WebClient();

      byte[] buffer = myWebClient.DownloadData (YAHOO_API_URL);

      string downloadData = Encoding.ASCII.GetString(buffer);

      // you can call you rest of the code. here

      Hope this helps

      Thanks
      Deepu

  2. May 27, 2010 at 2:27 pm | #3

    If only I had a quarter for every time I came to deepumi.wordpress.com.. Incredible read!

  3. Rajini
    June 11, 2010 at 10:31 pm | #4

    Deepu,
    Its a great article. Goos Job on it…you saved my day!

  4. murali
    March 15, 2012 at 12:46 pm | #6

    is it possible that, passing the latitude and longitude values and getting the location name to a lable to display….in c#

    pls help me out

  1. March 28, 2010 at 5:58 am | #1

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 29 other followers

%d bloggers like this: