Created
January 30, 2019 03:39
-
-
Save yoheiMune/9835bb8832db1b3687a93798d756c72f to your computer and use it in GitHub Desktop.
Yahoo!ローカルサーチAPIを利用してマップにアノテーションを立てる
This file contains 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
// 検索される時に呼び出される. | |
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { | |
// キーボードを閉じます. | |
searchBar.resignFirstResponder() | |
// 検索ワードがなければ終了. | |
guard let searchTerm = searchBar.text else { | |
return | |
} | |
// 検索条件を作成します. | |
let params: [String: Any] = [ | |
"appid" : API_KEY, | |
"query" : searchTerm, | |
"lat" : self.mapView.region.center.latitude, | |
"lon" : self.mapView.region.center.longitude, | |
"dist" : 1, | |
"results" : 10 | |
] | |
// Yahoo!ローカルサーチAPIのエンドポイント | |
let url = "https://map.yahooapis.jp/search/local/V1/localSearch" | |
// APIをコールする. | |
let request = Alamofire.request(url, method: .get, parameters: params) | |
// レスポンスを受け取ります. | |
request.responseString { response in | |
// 成功した場合. | |
if response.result.isSuccess { | |
// XML文字列を取得します. | |
let xmlString = response.result.value! | |
// XMLを読み込みます. | |
let xml = SWXMLHash.parse(xmlString) | |
// 検索結果の一覧を取得します. | |
let features = xml["YDF"]["Feature"] | |
// 1件ずつ読み取って、アノテーションとして表現します. | |
for feature in features.all { | |
// 名前と緯度経度を取得します. | |
if let name = feature["Name"].element?.text, | |
let lonlat = feature["Geometry"]["Coordinates"].element?.text { | |
let arr = lonlat.components(separatedBy: ",") | |
let lon = arr[0] | |
let lat = arr[1] | |
// マップに追加します. | |
let annotation = MKPointAnnotation() | |
annotation.coordinate = CLLocationCoordinate2D( | |
latitude: Double(lat)!, | |
longitude: Double(lon)! | |
) | |
annotation.title = name | |
self.mapView.addAnnotation(annotation) | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment