In this tutorial you will learn, how you can get the latitude and longitude of an address using Google API in C#.
Google provide the following API url by returning an XML result when you passing a location address on the url.
http://maps.googleapis.com/maps/api/geocode/xml?address=[query address]&sensor=[true or false] ex: http://maps.googleapis.com/maps/api/geocode/xml?address=Sydney NSW Australia&sensor=false
sensor attribute define whether your device has a GPS sensor or not. If you develop an application through mobile that has GPS capability then you set the sensor value to true.
Let's starts with the coding in C#
// Import the following namespaces using System.Xml; using System.Xml.XPath;
Create the following function that will return a string containing latitude and longitude in separated comma.
public string GetLongitudeAndLatitude(string address, string sensor) { string urlAddress = "http://maps.googleapis.com/maps/api/geocode/xml?address=" + HttpUtility.UrlEncode(address) + "&sensor=" + sensor; string returnValue = ""; try { XmlDocument objXmlDocument = new XmlDocument(); objXmlDocument.Load(urlAddress); XmlNodeList objXmlNodeList = objXmlDocument.SelectNodes("/GeocodeResponse/result/geometry/location"); foreach (XmlNode objXmlNode in objXmlNodeList) { // GET LONGITUDE returnValue = objXmlNode.ChildNodes.Item(0).InnerText; // GET LATITUDE returnValue += "," + objXmlNode.ChildNodes.Item(1).InnerText; } } catch { // Process an error action here if needed } return returnValue; }
Here is how you use it, you just need to pass an address value and a sensor value.
string geoValue = GetLongitudeAndLatitude("32 george Sydney NSW Australia", "false");