Parse-Parse使用C#获取Google地理编码API的纬度和经度



我有这个代码,我需要在Google Geocoding API上获取,只有纬度和经度位于"Geometry"节点,但不知道如何做到这一点,我的教程只用于列表,但我只需要选择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的一个对象中?

您应该使用像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!

我已经解决了这个问题。更改此代码的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;
        }

最新更新