通过C#webforms asp.net中的google map api从下拉列表中的选定城市中获取textbox1和textbox2的纬度和经度

拉西什·克里希纳

我需要得到纬度和经度textbox1,并textbox2从通过谷歌地图API中的下拉列表中选择城市。我正在使用C#和ASP .NET Web窗体。

这是我尝试的代码:

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;

     }
 }
KrzysztofKaźmierczak

这是您致电获取Google Maps geocoder 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();
    }

您必须记住对地址字符串进行编码,其中可能包含一些非法字符,而这些字符不能在querystring中使用。

Geocoder回应为json格式,您可以自己解析它,也可以使用为此设计的一些工具。在工作的小提琴中,我基于json响应(使用json2csharp.com创建了一些c#类

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序列化器反序列化对GeocodeResponse的json响应

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));

您可以尝试的工作拨弄这一点。它是控制台应用程序,但我相信您可以将其快速转换为Webform应用程序。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

Related 相关文章

热门标签

归档