This is a code snippet from a 'gecode' class I wrote in C#. This is the portion that retrieves the longitude and latitude for either a postal code or an address of some sort. The function retrieves the co-ordinates via a web request (WebRequest) to geocoder.ca. The response from geocoder.ca is then loaded into an XmlDocument, and parsed.
This code is meant to be integrated into a proximity search engine, to enable people to search for businesses by distance. But you could build it into your Windows applications as well. In my case, I built this into a geocoder class, and then created read-only properties for the longitude/latitude.
protected decimal longitude;
protected decimal lattitude;
protected string url = "http://geocoder.ca/?geoit=XML&";
protected string postalCode;
protected string address;
// your code to set postal code or address here
// check for valid format of postal code
public bool GetGeocode()
if (postalCode != null)
{
url += "postal=" + postalCode;
}
else
{
// no postal code, so look up based on street
url += "locate=" + address;
}
WebResponse response;
try
{
WebRequest request = WebRequest.Create(new Uri(url));
response = request.GetResponse();
}
catch (Exception e)
{
errorMessage = "website unavailable";
return false;
}
XmlTextReader xmlResponse = new XmlTextReader(response.GetResponseStream());
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(xmlResponse);
XmlNode LattNode = xmldoc.SelectSingleNode("geodata/latt");
XmlNode LongNode = xmldoc.SelectSingleNode("geodata/longt");
if (LattNode == null || LongNode == null)
{
errorMessage = "could not parse co-ordinates, check geocode data format";
return false;
}
if (LattNode.InnerText == "")
{
errorMessage = "could not retrieve co-ordinates for this address";
return false;
}
else
{
resp = LongNode.InnerText;
longitude = Convert.ToDecimal(LongNode.InnerText);
lattitude = Convert.ToDecimal(LattNode.InnerText);
return true;
}
}
6 Comments
Hi,
Thanks for your example.
I have one problem here.
I want to have all xml data for some range. Like I want all long/lat that belongs to postal1 & postal2.
How can I query this?
Thank you
Just create an array of the postal codes you want, loop through the array, and retrieve one for each.
Hi Justing,
I am using php and I was wondering if you have the same code for php.
Thanks much.
Sorry, I don't. Check the geocode.ca website, they have some API coding examples you may be able to use
Awesome site man! I know that aspunity.com has quite a bit of code snippets to accompany this!
hello,
thanks , after a long and hard searching i was found this article. it is very useful for me. i am really thanks full to u.