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=” + 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
Like this:
Like Loading...