把使用者輸入的地址轉換成經緯度座標,在 iOS 上透過 Core Location 的 CLGeocoder 就能完成,這個過程稱為正向地理編碼(forward geocoding)。
CLGeocoder *myGeocoder = [[CLGeocoder alloc] init];
[myGeocoder geocodeAddressString:_searchBar.text completionHandler:^(NSArray *placemarks, NSError *error) {
if ([placemarks count] > 0 && error == nil) {
CLPlacemark *firstPlacemark = [placemarks objectAtIndex:0];
NSLog(@"%f", firstPlacemark.location.coordinate.latitude);
NSLog(@"%f", firstPlacemark.location.coordinate.longitude);
}
else if ([placemarks count] == 0 && error == nil) {
NSLog(@"找不到對應的地標。");
}
else if (error != nil) {
NSLog(@"發生錯誤 = %@", error);
}
}];
geocodeAddressString:region:completionHandler: 限定國家或區域範圍。placemark.location.coordinate,而 placemark 本身還帶有 thoroughfare、locality、administrativeArea、country、postalCode 等結構化欄位,可以反過來組出完整地址。如果手上已經有經緯度,想反查地址,改用 CLLocation 建立物件後呼叫 reverseGeocodeLocation:completionHandler: 即可,回傳的同樣是 CLPlacemark 陣列,欄位用法完全一致。