Google Maps v3地理编码服务器端

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

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

void GoogleGeoCode(string address) { string url = "http://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 = "http://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

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