![](/img/trans.png)
[英]Google API to get address corresponding to Latitude and Longitude in C#
[英]Parse Parse to get Latitude and Longitude of the Google Geocoding API using C #
我有需要在Google Geocoding 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的一個對象中?
您應該使用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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.