How to extract latitude and longitude from Google Maps URL using C# winform Application programmatically?
CodePudding user response:
You can use the following code. You can change the urlGoogleMaps (string) to any other URL you like. This example is the location of the liberty statue in New York, USA.
public void YourCode()
{
string urlGoogleMaps = "https://www.google.com/maps/place/New York, NY, USA/@40.6893423,-74.0446546,18.75z/data=!4m5!3m4!1s0x89c24fa5d33f083b:0xc80b8f06e177fe62!8m2!3d40.7127753!4d-74.0059728";
Coordination LibertyStatue = new Coordination(urlGoogleMaps);
Console.WriteLine("Statue of Liberty:");
Console.WriteLine("Latitude: " LibertyStatue.Latitude);
Console.WriteLine("Longitude: " LibertyStatue.Longitude);
Console.WriteLine("Height: " LibertyStatue.Height);
}
public class Coordination
{
public float Latitude;
public float Longitude;
public float Height;
public Coordination(string urlGoogleMaps)
{
string rawCoords = urlGoogleMaps.Split('/').Where(c => c.StartsWith("@") && c.EndsWith("z")).FirstOrDefault();
Latitude = float.Parse(rawCoords.Split(',')[0].TrimStart('@'));
Longitude = float.Parse(rawCoords.Split(',')[1]);
Height = float.Parse(rawCoords.Split(',')[2].TrimEnd('z'));
}
}
Note; you might want to add some preventions for when the url is not fit to meet these methods.
