【问题标题】:Parse Parse to get Latitude and Longitude of the Google Geocoding API using C #Parse Parse 使用 C# 获取 Google Geocoding API 的纬度和经度
【发布时间】:2013-11-27 11:38:50
【问题描述】:

我有这段代码需要在谷歌地理编码 API 上获取,只有位于“几何”节点中的纬度和经度,但不知道该怎么做,我的教程仅适用于列表,但我只需选择 JSon 中包含的经纬度之一即可。

API JSON:

  {
       "results" : [
          {
             "address_components" : [
                {
                   "long_name" : "1600",
                   "short_name" : "1600",
                   "types" : [ "street_number" ]
                },
                {
                   "long_name" : "Amphitheatre Pkwy",
                   "short_name" : "Amphitheatre Pkwy",
                   "types" : [ "route" ]
                },
                {
                   "long_name" : "Mountain View",
                   "short_name" : "Mountain View",
                   "types" : [ "locality", "political" ]
                },
                {
                   "long_name" : "Santa Clara",
                   "short_name" : "Santa Clara",
                   "types" : [ "administrative_area_level_2", "political" ]
                },
                {
                   "long_name" : "California",
                   "short_name" : "CA",
                   "types" : [ "administrative_area_level_1", "political" ]
                },
                {
                   "long_name" : "United States",
                   "short_name" : "US",
                   "types" : [ "country", "political" ]
                },
                {
                   "long_name" : "94043",
                   "short_name" : "94043",
                   "types" : [ "postal_code" ]
                }
             ],
             "formatted_address" : "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
             "geometry" : {
                "location" : {
                   "lat" : 37.42291810,
                   "lng" : -122.08542120
                },
                "location_type" : "ROOFTOP",
                "viewport" : {


           "northeast" : {
                  "lat" : 37.42426708029149,
                  "lng" : -122.0840722197085
               },
               "southwest" : {
                  "lat" : 37.42156911970850,
                  "lng" : -122.0867701802915
               }
            }
         },
         "types" : [ "street_address" ]
      }
   ],
   "status" : "OK"
}   

namespace Traveler
{

    public partial class MainPage : PhoneApplicationPage
    {        

        // Constructor
        public MainPage()
        {
            InitializeComponent();

            // Set the data context of the listbox control to the sample data
            DataContext = App.ViewModel;
        }

        // Load data for the ViewModel Items
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (!App.ViewModel.IsDataLoaded)
            {
                App.ViewModel.LoadData();
            }
        }

        private void btnSearch_ActionIconTapped(object sender, EventArgs e)
        {
            try
            {
                WebClient webClient = new WebClient();
                webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
                webClient.DownloadStringAsync(new System.Uri("http://maps.googleapis.com/maps/api/geocode/json?address=" + txtSearch.Text));
            }
            catch
            {
                //criar if para verificar conexão   
                MessageBox.Show("Try again!");
            }
        }

        private void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    // Showing the exact error message is useful for debugging. In a finalized application, 
                    // output a friendly and applicable string to the user instead. 
                    MessageBox.Show(e.Error.Message);
                });
            }
            else
            {
                // Save the feed into the State property in case the application is tombstoned. 
                this.State["json"] = e.Result;
                ParserJSON(e.Result);
            }
        }

        private List<clsRoute> ParserJSON(string pJSON)
        {
            //criar um objeto lista do tipo clsRoute
            List<clsRoute> lista = new List<clsRoute>();

            //Se o JSON está presente
            if (pJSON != null)
            { 
                //Faz a conversão (parse) para um tipo jObject
                JObject jObj = JObject.Parse(pJSON);

                //Le o objeto da lista inteira
                JObject jObjectResults = (JObject)jObj["results"];

                //Le o objeto da lista results
                JArray results = (JArray)jObjectResults["address_components"]["geometry"];
                foreach (JObject address_components in results)
                {
                    clsRoute c = new clsRoute()
                    {
                        latitude = (Double)address_components["lat"],
                        longitude = (Double)address_components["lng"]
                    };
                }
                //Task here
            }
            return lista;
        }
    }
}

如何将纬度和经度添加到 ClsRoute 的 ONE 对象中?

【问题讨论】:

  • 是的!但问题是如何读取“位置”节点,但我已经解决了问题,感谢您的时间!

标签: c# json parsing windows-phone-7 latitude-longitude


【解决方案1】:

您应该使用像json2csharp.com 这样的网站来创建基于 json 的类。使用该网站,我获得了以下课程。

public class AddressComponent
{
    public string long_name { get; set; }
    public string short_name { get; set; }
    public List<string> types { get; set; }
}

public class Location
{
    public double lat { get; set; }
    public double lng { get; set; }
}

public class Northeast
{
    public double lat { get; set; }
    public double lng { get; set; }
}

public class Southwest
{
    public double lat { get; set; }
    public double lng { get; set; }
}

public class Viewport
{
    public Northeast northeast { get; set; }
    public Southwest southwest { get; set; }
}

public class Geometry
{
    public Location location { get; set; }
    public string location_type { get; set; }
    public Viewport viewport { get; set; }
}

public class Result
{
    public List<AddressComponent> address_components { get; set; }
    public string formatted_address { get; set; }
    public Geometry geometry { get; set; }
    public List<string> types { get; set; }
}

public class RootObject
{
    public List<Result> results { get; set; }
    public string status { get; set; }
}

json2csharp 在创建重复对象方面确实很臭。我会删除 Northwest 和类似的课程。仅将它们的使用替换为 Location 对象。

使用 JSON.Net(又名 Newtonsoft.JSON)我可以很容易地反序列化字符串。

var root = JsonConvert.Deserialize<RootObject>(e.Result);
// use the results!

【讨论】:

  • 谢谢,但我已经解决了问题,“Newtonsoft”是一个非常简单的 dll,用于读取由巴西人创建的 JSON。谢谢你的时间好吗?
  • Json.Net 是解析 json 的“事实上的”解决方案。使用该库比自己解析要容易得多。
【解决方案2】:

我已经解决了这个问题。 更改此代码的 ParseJSON 函数:

private GeoCoordinate ParserJSON(string pJSON)
        {   
            //Se o JSON está presente
            if (pJSON != null)
            {
                try
                {
                    //Faz a conversão (parse) para um tipo jObject
                    JObject jObj = JObject.Parse(pJSON);

                    //Le o objeto da lista inteira
                    JArray results = jObj["results"] as JArray;

                    JToken firstResult = results.First;
                    JToken location = firstResult["geometry"]["location"];

                    GeoCoordinate coord = new GeoCoordinate()
                    {
                        Latitude = Convert.ToDouble(location["lat"].ToString()),
                        Longitude = Convert.ToDouble(location["lng"].ToString())
                    };


                }
                catch 
                {
                    ///todo: if para verificar conexão
                    MessageBox.Show("Verify your network connection!");
                }

            }
            return null;
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多