I have a address in string like "444 NE Ravenna Blvd, Seattle, WA" , now how can I get the lat/long of this address using Google maps or any other services in C#.
Basically need to convert address into Lat-long using C#.
You can do it using Nuget Package GoogleMaps.LocationServices in C#.
Here is how to use it:
Install-Package GoogleMaps.LocationServices?
if you are using .NET 4.6 or below, instal older version like 1.2.0
public static void GetLatLongFromAddress(string address)
{
//replace APIKey your Google API Key here
var locationService = new GoogleLocationService("APIKey");
var point = locationService.GetLatLongFromAddress(address);
var latitude = point.Latitude;
var longitude = point.Longitude;
// Save lat/long values to DB...
}?
That's it, simple to use and get Lat-long from address.
With the helpf of above API, you can also convert lat-long into address using C#.
You can also use below code, by passing address and call URL.
string url = "http://maps.google.com/maps/api/geocode/xml?address=" + address+ "&sensor=false";
WebRequest request = WebRequest.Create(url);
using (WebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
DataSet dsResult = new DataSet();
dsResult.ReadXml(reader);
DataTable dtCoordinates = new DataTable();
dtCoordinates.Columns.AddRange(new DataColumn[4] { new DataColumn("Id", typeof(int)),
new DataColumn("Address", typeof(string)),
new DataColumn("Latitude",typeof(string)),
new DataColumn("Longitude",typeof(string)) });
foreach (DataRow row in dsResult.Tables["result"].Rows)
{
string geometry_id = dsResult.Tables["geometry"].Select("result_id = " + row["result_id"].ToString())[0]["geometry_id"].ToString();
DataRow location = dsResult.Tables["location"].Select("geometry_id = " + geometry_id)[0];
dtCoordinates.Rows.Add(row["result_id"], row["formatted_address"], location["lat"], location["lng"]);
}
}
return dtCoordinates;
}
It will give you lat/long in C# datatable.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly