获取经纬度textbox1和textbox2从下拉列表中通过谷歌地图api在下拉列表中选择城市webforms asp.net
问题描述:
我需要从经过谷歌地图api的下拉列表中选择城市textbox1
和textbox2
获取经纬度。我使用C#和ASP .NET Web窗体。获取经纬度textbox1和textbox2从下拉列表中通过谷歌地图api在下拉列表中选择城市webforms asp.net
这是我试过的代码:
function sayHello()
{
string url = "https://maps.googleapis.com/maps/api/geocode/json?address=+Dropdownlist1.Text+Dropdownlist2.Text+Dropdownlist3.Text+&sensor=false");
WebRequest request = WebRequest.Create(url);
using (WebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
string address = document.getElementById(reader).ToString;
float latitude;
float longitude;
//var geocoder = new google.maps.Geocoder();
latitude = results[0].geometry.location.lat();
longitude = results[0].geometry.location.lng();
document.getElementById("TextBox1").Text = latitude;
document.getElementById("TextBox2").Text = longitude;
}
}
答
这是你如何拨打电话,以获得谷歌地图地理编码JSON响应:
string json = string.Empty;
string url = string.Format("https://maps.googleapis.com/maps/api/geocode/json?address={0}&sensor=false", HttpUtility.UrlEncode(address));
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
json = reader.ReadToEnd();
}
你要记住编码您的地址字符串,可能包含一些非法字符,这些字符不能在查询字符串中使用。
地理编码器响应采用json格式,您可以自行解析或使用一些专为此设计的工具。在我工作的小提琴我创建了一些C#类基础上(使用json2csharp.com)JSON响应:
public class Location
{
public double lat
{
get;
set;
}
public double lng
{
get;
set;
}
}
public class Geometry
{
public Location location
{
get;
set;
}
}
public class Result
{
public Geometry geometry
{
get;
set;
}
}
public class GeocodeResponse
{
public List<Result> results
{
get;
set;
}
}
然后我反序列化使用Json.NET JSON序列JSON响应GeocodeResponse。
GeocodeResponse gr = JsonConvert.DeserializeObject<GeocodeResponse>(json);
Console.WriteLine(string.Format("lat: {0}, long: {1}", gr.results[0].geometry.location.lat, gr.results[0].geometry.location.lng));
您可以尝试的工作fiddle这一点。它是控制台应用程序,但我相信你可以快速将其转换为你的webform应用程序。
此致敬礼!
Krzysztof