C#でGoogle Maps APIを使う(2点間の距離を取得)

Google Maps APIを使って2点間の距離を取得するメソッドを実装してみました。

  1. public static double GetDistance(string origin, string destination, string apiKey) {
  2. double ret = 0;
  3. WebResponse response = null;
  4. try {
  5. string url = @"https://maps.googleapis.com/maps/api/distancematrix/json?origins=" +
  6. origin + "&destinations=" + destination + "&key=" + apiKey;
  7.  
  8. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
  9. response = request.GetResponse();
  10. Stream dataStream = response.GetResponseStream();
  11. StreamReader sReader = new StreamReader(dataStream);
  12. string jsonString = sReader.ReadToEnd();
  13. Debug.Write(jsonString);
  14.  
  15. var jo = JObject.Parse(jsonString);
  16. JToken jt = jo.SelectToken("$.rows..elements..distance.value");
  17. ret = double.Parse(StringUtil.NullBlankToZero(jt.ToString()));
  18.  
  19. return ret;
  20. } finally {
  21. response.Close();
  22. }
  23. }

例えば「origin:東京」-「destination:大阪」を指定してリクエストを投げると、以下の形式のJSONが返されるので、
JSONPathを使って、距離の部分を抜き出して戻り値にセットしています。

●例)「東京」-「大阪」間でリクエストを投げた時のJSON取得結果
  1. {
  2. "destination_addresses" : [ "Osaka, Osaka Prefecture, Japan" ],
  3. "origin_addresses" : [ "Tokyo, Japan" ],
  4. "rows" : [
  5. {
  6. "elements" : [
  7. {
  8. "distance" : {
  9. "text" : "513 km",
  10. "value" : 512545
  11. },
  12. "duration" : {
  13. "text" : "6 hours 16 mins",
  14. "value" : 22563
  15. },
  16. "status" : "OK"
  17. }
  18. ]
  19. }
  20. ],
  21. "status" : "OK"
  22. }
  23.  

0 件のコメント:

コメントを投稿

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

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