This function returns the latitude and longitude for the supplied address. It uses the google's geocode api to get the address info.
public static Dictionary<string, decimal> GetLocationLngLat(string address)
{
//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=" +
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;
Dictionary<string, decimal> location = new Dictionary<string, decimal>();
while (xmlReader.Read())
{
xmlReader.MoveToElement();
switch (xmlReader.Name)
{
case "lat":
if (!latread)
{
xmlReader.Read();
location["Latitude"] = Convert.ToDecimal(xmlReader.Value);
latread = true;
}
break;
case "lng":
if (!longread)
{
xmlReader.Read();
location["Longitude"] = Convert.ToDecimal(xmlReader.Value);
longread = true;
}
break;
}
}
return location;
}
catch (Exception ex)
{
throw new Exception("An Error Occured" + ex.Message);
}
}
public static Dictionary<string, decimal> GetLocationLngLat(string address)
{
//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=" +
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;
Dictionary<string, decimal> location = new Dictionary<string, decimal>();
while (xmlReader.Read())
{
xmlReader.MoveToElement();
switch (xmlReader.Name)
{
case "lat":
if (!latread)
{
xmlReader.Read();
location["Latitude"] = Convert.ToDecimal(xmlReader.Value);
latread = true;
}
break;
case "lng":
if (!longread)
{
xmlReader.Read();
location["Longitude"] = Convert.ToDecimal(xmlReader.Value);
longread = true;
}
break;
}
}
return location;
}
catch (Exception ex)
{
throw new Exception("An Error Occured" + ex.Message);
}
}
No comments:
Post a Comment