【Windows Phone 8】地理位置結合Google Geocoding API
前言:
使用地理位置得到了一串長的數字(經緯度),
但你也不知道那代表什麼除非你有超強的記憶力才能將全世界的地理位置記起來,
這時結合Google API來將經緯度轉換為地址,較符合一般輸出在畫面上的結果。
參考【Google Geocoding API】【反向地理編碼 (地址查閱)】
實作:
Step-1 將【geolocator_PositionChanged】事件稍作修改(這部分只實作應用程式啟動狀態才使用)
說明:加入一事件在位置改變時將經度緯度傳入副程式中
void geolocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args)
{
   if(!App.location)
   {
         Dispatcher.BeginInvoke(() =>
        {
             LatitudeTextBlock.Text = args.Position.Coordinate.Latitude.ToString("0.000000");
             LongitudeTextBlock.Text = args.Position.Coordinate.Longitude.ToString("0.000000");
             LatLng(args.Position.Coordinate.Latitude.ToString("0.000000"), args.Position.Coordinate.Longitude.ToString("0.000000"));
        });
   }
   else
   {
        ShellToast toast = new ShellToast();
        toast.Title = "位置:";
        toast.Content = args.Position.Coordinate.Latitude.ToString("0.00") + ":" + args.Position.Coordinate.Longitude.ToString("0.00");
        toast.Show();
   }
            
}
Step-2 建立【LatLng】副程式
public void LatLng(string Lat, string Lng)
{
    WebClient wc = new WebClient();
    //將經緯度傳入Google Geocoding API進行反向地理編碼
    wc.DownloadStringAsync(new Uri("http://maps.googleapis.com/maps/api/geocode/json?latlng=" + Lat + "," + Lng + "&sensor=false", UriKind.Absolute));
    wc.DownloadStringCompleted += wc_DownloadStringCompleted;
}
Step-3 建立類別
說明:使用Google Geocoding API回傳的資料型態為Json格式,
建一類別來解析資料(Google API 也可回傳XML格式)
public class Rootobject
{
   public List<Result> results { get; set; }
   public string status { get; set; }
}
public class Result
{
   public List<Address_Components> address_components { get; set; }
   public string formatted_address { get; set; }
   public string[] types { get; set; }
}
public class Address_Components
{
   public string long_name { get; set; }
   public string short_name { get; set; }
   public string[] types { get; set; }
}
Step-4 【wc_DownloadStringCompleted】事件
說明:利用Json.Net反序列化,並將解
private void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    var api = JsonConvert.DeserializeObject<Rootobject>(e.Result);
    foreach (var i in api.results)
    {
         foreach(var a in i.address_components)
         {
             MessageBox.Show(a.short_name);
             break;
         }
    }
}
 
執行結果:
 
