C#でGoogle Maps APIを使う(2点間の移動時間を取得)

先日の続編で2点間の移動時間を取得するメソッドを実装してみました。
ポイントは、移動モードを指定するところです。
現在、日本での利用では、driving(車), walking(徒歩)の2種類の移動時間取得のみに制限されています。

  1. public class GoogleMapsApiUtil {
  2.  
  3. public enum MovingMode : int {
  4. driving = 1, //車
  5. //transit, //電車 ←日本ではサポート外
  6. walking, //徒歩
  7. //bicycling //自転車 ←日本ではサポート外
  8. }
  9.  
  10. ///
  11. /// 2点間の車での移動時間を取得
  12. ///
  13. ///
  14. ///
  15. ///
  16. ///
  17. public static double GetDuration(string origin, string destination, MovingMode mode, string apiKey) {
  18. double ret = 0;
  19. WebResponse response = null;
  20. try {
  21. string url = @"https://maps.googleapis.com/maps/api/distancematrix/json?origins=" +
  22. origin + "&destinations=" + destination + "&mode=" + mode.ToString() + "&key=" + apiKey;
  23.  
  24. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
  25. response = request.GetResponse();
  26. Stream dataStream = response.GetResponseStream();
  27. StreamReader sReader = new StreamReader(dataStream);
  28. string jsonString = sReader.ReadToEnd();
  29. Debug.Write(jsonString);
  30.  
  31. var jo = JObject.Parse(jsonString);
  32. JToken jt = jo.SelectToken("$.rows..elements..duration.value");
  33. ret = double.Parse(StringUtil.NullBlankToZero(jt.ToString()));
  34.  
  35. return ret;
  36. } finally {
  37. response.Close();
  38. }
  39. }
  40. }

0 件のコメント:

コメントを投稿

厳選 Visual Studioの便利なショートカット

  エラー箇所にジャンプ 「Ctrl + Shift + F12」 ブレークポイント 設定/解除 「F9」 有効化/無効化 「Ctrl + F9」 ViEmu特有 「:ls」:バッファナンバーのリストを表示。 「:b2」:バッファ2のファイルを開く。 「:n」:次のバッファのファ...