I have this code that I need to get on Google Geocoding API, only the latitude and longitude located in the "Geometry" node, but do not know how to do this, I have the tutorial is only for lists, but I need to pick only one of latitudes and longitudes contained in JSon.
我有这个代码,我需要使用Google地理编码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;
}
}
}
How to add the Latitude and Longitude to ONE object of ClsRoute?
如何将纬度和经度添加到ClsRoute的一个对象?
2 个解决方案
#1
0
You should use a site like json2csharp.com to create classes based on the json. Using that site I got the following classes.
您应该使用像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 does stink about creating duplicate objects. I would remove the Northwest
and like classes. Replace the use of them with only the Location
object.
json2csharp确实很难创建重复的对象。我会删除西北和类似的课程。仅使用Location对象替换它们的使用。
Using JSON.Net (aka Newtonsoft.JSON) I can deserialize the string very easily.
使用JSON.Net(又名Newtonsoft.JSON)我可以很容易地反序列化字符串。
var root = JsonConvert.Deserialize<RootObject>(e.Result);
// use the results!
#2
0
I've solved this problem. Change the ParseJSON function for this code:
我已经解决了这个问题。更改此代码的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;
}
#1
0
You should use a site like json2csharp.com to create classes based on the json. Using that site I got the following classes.
您应该使用像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 does stink about creating duplicate objects. I would remove the Northwest
and like classes. Replace the use of them with only the Location
object.
json2csharp确实很难创建重复的对象。我会删除西北和类似的课程。仅使用Location对象替换它们的使用。
Using JSON.Net (aka Newtonsoft.JSON) I can deserialize the string very easily.
使用JSON.Net(又名Newtonsoft.JSON)我可以很容易地反序列化字符串。
var root = JsonConvert.Deserialize<RootObject>(e.Result);
// use the results!
#2
0
I've solved this problem. Change the ParseJSON function for this code:
我已经解决了这个问题。更改此代码的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;
}