摘要:Google Geocoding API 應用
上一篇介紹了Google Geocoding API ,這篇就針對Google Geocoding API 如何使用
1.把上一篇的JSON格式的網址打在瀏覽器上,之後把該網頁Ctrl+A整篇複製下來,
並貼到 http://json2csharp.com/ ,點Generate後會產生我們要的Json對應的類別欄位。
public class AddressComponent
{
public string long_name { get; set; }
public string short_name { get; set; }
public List 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 address_components { get; set; }
public string formatted_address { get; set; }
public Geometry geometry { get; set; }
public bool partial_match { get; set; }
public List types { get; set; }
}
public class RootObject
{
public List results { get; set; }
public string status { get; set; }
}
2.開啟你的專案並加入一個類別檔,建好檔命完名之後就可以把上列程式碼全部貼進去可以使用它他了。
3.之後我們要載入JSON.NET的套件,PM> Install-Package Newtonsoft.Json
4.接著 引用以下三個
using Newtonsoft.Json;
using System.Diagnostics;
using System.Text;
到這裡就完成一半了,接著就是要用程式抓取網頁資訊了。
小編是使用WebClient抓取該網頁資訊,以下是我的程式碼:
WebClient wc = new WebClient();
wc.Encoding = Encoding.UTF8;
string json_data = "http://maps.googleapis.com/maps/api/geocode/json?address=台灣台中市三民路三段129號&sensor=false";
wc.DownloadStringAsync(new Uri(json_data));
wc.DownloadStringCompleted += (sender2, e2) =>
{
try
{
RootObject userInfo = JsonConvert.DeserializeObject(e2.Result);
MessageBox.Show("經度="+userInfo.results[0].geometry.location.lat + "\n"+
"緯度=" + userInfo.results[0].geometry.location.lng + "\n");
}
catch
{
MessageBox.Show("錯誤訊息: " + e2.Error.Message);
}
};
如此一來就可以利用WebClient來抓取JSON資料 ,之後放進去你建好的JOSN類別檔。
然後就可以把資訊類別化,當物件做使用了。