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

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

public class GoogleMapsApiUtil {

    public enum MovingMode : int {
        driving = 1, //車
        //transit, //電車 ←日本ではサポート外
        walking, //徒歩
        //bicycling //自転車 ←日本ではサポート外
    }

    /// 
    /// 2点間の車での移動時間を取得
    /// 
    /// 
    /// 
    /// 
    /// 
    public static double GetDuration(string origin, string destination, MovingMode mode, string apiKey) {
        double ret = 0;
        WebResponse response = null;
        try {
            string url = @"https://maps.googleapis.com/maps/api/distancematrix/json?origins=" +
                origin + "&destinations=" + destination + "&mode=" + mode.ToString() + "&key=" + apiKey;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            response = request.GetResponse();
            Stream dataStream = response.GetResponseStream();
            StreamReader sReader = new StreamReader(dataStream);
            string jsonString = sReader.ReadToEnd();
            Debug.Write(jsonString);

            var jo = JObject.Parse(jsonString);
            JToken jt = jo.SelectToken("$.rows..elements..duration.value");
            ret = double.Parse(StringUtil.NullBlankToZero(jt.ToString()));

            return ret;
        } finally {
            response.Close();
        }
    }
}

0 件のコメント:

コメントを投稿

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

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