LoginSignup
5
3

More than 5 years have passed since last update.

SwiftでGoogle Maps Elevation APIを利用して地点の標高を取得する

Posted at

概要

Google Maps Elevation APIにリクエストして標高の情報を取得する実装のメモです。

Elevation APIについて

Google Maps Elevation API のシンプルなインターフェースを使用すると、
地球上の任意の地点における標高データを問い合わせることができます。
さらに、任意のルート上で標高データをサンプリングするようリクエストして、
そのルートに沿った標高の変化を計算することもできます。

こういったことができます。
公式のデベロッパーガイドはこちらです。

実装してみる

準備:APIキーの取得

APIのリクエストにはAPIキーが必要です。
このページを開いて、「キーを取得する」ボタンから取得します。

実装

簡単な例として、ViewControllerが表示されたタイミングでAPIリクエストを行うように実装しました。

import UIKit

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        request()
    }

    private func request() {
        let configuration = URLSessionConfiguration.default
        let session = URLSession(configuration: configuration)

        let apiKey = "<YOUR_API_KEY>"
        let url = "https://maps.googleapis.com/maps/api/elevation/json?key=\(apiKey)&locations=35.360556,138.727778"
        let task = session.dataTask(with: URL(string: url)!) { (data, response, error) in
            if let error = error {
                print(error)
            } else {
                let json = try! JSONSerialization.jsonObject(with: data!, options: []) as! [String: Any]
                if let results = json["results"] as? [[String: Any]] {
                    for result in results {
                        if let location = result["location"] as? [String: Double] {
                            print(location["lat"])
                            print(location["lng"])
                        }
                        print(result["elevation"] as? Double)
                    }
                }
            }
        }
        task.resume()
    }
}

の部分を事前準備で取得した自分のAPIキーに置き換えればAPIリクエストが成功すると思います。
locationsには標高を取得したい地点の緯度・経度を指定してください。
上記の例では富士山が指定されています(緯度:35.360556, 経度:138.727778)

複数の位置情報をリクエストする

複数の地点の標高を取得したい場合は、リクエストパラメータのlocationsに複数の緯度経度を渡します。

  • locations=40.714728,-73.998672|-34.397,150.644

地点と地点は|(パイプ)で接続します。

APIのレスポンス

{
   "results" : [
      {
         "elevation" : 1608.637939453125,
         "location" : {
            "lat" : 39.73915360,
            "lng" : -104.98470340
         },
         "resolution" : 4.771975994110107
      }
   ],
   "status" : "OK"
}

ドキュメント通りですが、こういう感じで返ってきます。

以上、Google Maps Elevation APIを使って標高情報を取得する実装のメモでした。

5
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3