国土交通省 国土地理院 から公開されている 標高API を使いたいと思います。
WebAPI の結果をJSONデータで取得して、パース処理… どうやるんだろう…とググりました。
SwiftJSON ? がよくヒットしたけど、Swift4 で動かせなかったので…却下 ^^;;
最終的に、以下の2つの記事を参考にしたら、予想以上にあっさりと実現できました。
Codable というモノのおかげですごく簡単に実装できるようになったみたい。
最終的にこんな感じになりました。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//呼び出し側の記述例 | |
//WebAPI | |
let webApi = Geospatial() | |
webApi.getElevation(coordinate, closure: { (json) in | |
if let elevation = json?.elevation { | |
print(elevation) | |
} | |
}) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import CoreLocation | |
class Geospatial: NSObject { | |
//JSON 全体の構成 | |
struct Json: Codable { | |
let elevation: Double | |
let hsrc: String | |
} | |
} | |
// MARK: - | |
extension Geospatial { | |
//Web 問い合わせ | |
public func getElevation(_ coordinate: CLLocationCoordinate2D?, closure:@escaping (_ json: Json?)->()) { | |
//前提条件 | |
guard let coordinate = coordinate else { | |
return | |
} | |
let url_text = String(format:"https://cyberjapandata2.gsi.go.jp/general/dem/scripts/getelevation.php?lat=%f&lon=%f&outtype=JSON", coordinate.latitude, coordinate.longitude) | |
if let url = URL(string: url_text) { | |
let task = URLSession.shared.dataTask(with: url, completionHandler: { (data, responce, error) in | |
//前提条件 | |
if let error = error { | |
print(error) | |
return | |
} | |
//Jsonをパース | |
let json = self.decode(data) | |
//*** callback *** | |
DispatchQueue.main.async() { | |
closure(json) | |
} | |
}) | |
task.resume() | |
} | |
} | |
//JSONデータの読み込み | |
private func decode(_ json: Data?) -> Json? { | |
//前提条件 | |
guard let json = json else { | |
return nil | |
} | |
//データ読み込み | |
let decoder = JSONDecoder() | |
if let data = try? decoder.decode(Json.self, from: json) { | |
//正常終了 | |
return data | |
} | |
//異常終了 | |
return nil | |
} | |
} |
One Comment