Csharp/C#教程:Google Maps v3地理编码服务器端分享


Google Maps v3地理编码服务器端

我正在使用ASP.NET MVC 3和Google Maps v3。 我想在动作中进行地理编码。 这是将有效地址传递给Google并获得经度和经度。 我见过的所有关于地理编码的在线样本都处理了客户端地理编码。 你会如何在使用C#的动作中做到这一点?

我不确定我是否理解正确,但这是我的方式(如果你有兴趣)

void GoogleGeoCode(string address) { string url = "https://maps.googleapis.com/maps/api/geocode/json?sensor=true&address="; dynamic googleResults = new Uri(url + address).GetDynamicJsonObject(); foreach (var result in googleResults.results) { Console.WriteLine("[" + result.geometry.location.lat + "," + result.geometry.location.lng + "] " + result.formatted_address); } } 

在这里使用扩展方法和Json.Net

LB的解决方案对我有用。 但是我遇到了一些运行时绑定问题,并且在我可以使用之前必须先抛出结果

  public static Dictionary GoogleGeoCode(string address) { var latLong = new Dictionary(); const string url = "https://maps.googleapis.com/maps/api/geocode/json?sensor=true&address="; dynamic googleResults = new Uri(url + address).GetDynamicJsonObject(); foreach (var result in googleResults.results) { //Have to do a specific cast or we'll get a C# runtime binding exception var lat = (decimal)result.geometry.location.lat; var lng = (decimal) result.geometry.location.lng; latLong.Add("Lat", lat); latLong.Add("Lng", lng); } return latLong; } 

由于新的Google API要求使用有效的API密钥,我遇到了问题。 为了使工作正常,我修改了代码以将密钥附加到地址并将URL更改为https

上述就是C#学习教程:Google Maps v3地理编码服务器端分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

 public Dictionary GoogleGeoCode(string address) { var latLong = new Dictionary(); string addressReqeust = address + "&key=your api key here"; const string url = "https://maps.googleapis.com/maps/api/geocode/json?sensor=true&address="; dynamic googleResults = new Uri(url + addressReqeust).GetDynamicJsonObject(); foreach (var result in googleResults.results) { //Have to do a specific cast or we'll get a C# runtime binding exception var lat = (decimal)result.geometry.location.lat; var lng = (decimal)result.geometry.location.lng; try { latLong.Add("Lat", lat); latLong.Add("Lng", lng); } catch (Exception ex) { } } return latLong; } 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/997145.html

(0)
上一篇 2021年12月26日
下一篇 2021年12月26日

精彩推荐