C# 从 Google 地理编码 API 获取纬度和经度
C# Getting lat and long from Google GeoCoding API
在我的 C# 项目中,我试图获取建筑物的纬度和经度位置。我使用此线程作为基础 Distance between addresses 并尝试对其进行调整以获取某个位置的纬度和经度。目前,从 API 获得 JSON 响应很好,它从 JSON 响应获得我想要的值。
这是我目前的代码
string requesturl = url;
string content = fileGetContents(requesturl);
JObject o = JObject.Parse(content);
user.Latitude = (double)o.SelectToken("results[0].geometry[0].location[0].lat");
user.Longitude = (double)o.SelectToken("results[0].geometry[0].location[0].lng");
protected string fileGetContents(string fileName)
{
string sContents = string.Empty;
string me = string.Empty;
try
{
if (fileName.ToLower().IndexOf("https:") > -1)
{
System.Net.WebClient wc = new System.Net.WebClient();
byte[] response = wc.DownloadData(fileName);
sContents = System.Text.Encoding.ASCII.GetString(response);
}
else
{
System.IO.StreamReader sr = new System.IO.StreamReader(fileName);
sContents = sr.ReadToEnd();
sr.Close();
}
}
catch { sContents = "unable to connect to server "; }
return sContents;
}
看起来问题在于您正在尝试访问几何图形和位置,就好像它们是列表一样。试试这个:
user.Latitude = (double)o.SelectToken("results[0].geometry.location.lat");
user.Longitude = (double)o.SelectToken("results[0].geometry.location.lng");
在我的 C# 项目中,我试图获取建筑物的纬度和经度位置。我使用此线程作为基础 Distance between addresses 并尝试对其进行调整以获取某个位置的纬度和经度。目前,从 API 获得 JSON 响应很好,它从 JSON 响应获得我想要的值。
这是我目前的代码
string requesturl = url;
string content = fileGetContents(requesturl);
JObject o = JObject.Parse(content);
user.Latitude = (double)o.SelectToken("results[0].geometry[0].location[0].lat");
user.Longitude = (double)o.SelectToken("results[0].geometry[0].location[0].lng");
protected string fileGetContents(string fileName)
{
string sContents = string.Empty;
string me = string.Empty;
try
{
if (fileName.ToLower().IndexOf("https:") > -1)
{
System.Net.WebClient wc = new System.Net.WebClient();
byte[] response = wc.DownloadData(fileName);
sContents = System.Text.Encoding.ASCII.GetString(response);
}
else
{
System.IO.StreamReader sr = new System.IO.StreamReader(fileName);
sContents = sr.ReadToEnd();
sr.Close();
}
}
catch { sContents = "unable to connect to server "; }
return sContents;
}
看起来问题在于您正在尝试访问几何图形和位置,就好像它们是列表一样。试试这个:
user.Latitude = (double)o.SelectToken("results[0].geometry.location.lat");
user.Longitude = (double)o.SelectToken("results[0].geometry.location.lng");