- Notifications
You must be signed in to change notification settings - Fork47
Address search and reverse geocoding in Swift or Objective-C on iOS, macOS, tvOS, and watchOS
License
mapbox/MapboxGeocoder.swift
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
MapboxGeocoder.swift makes it easy to connect your iOS, macOS, tvOS, or watchOS application to theMapbox Geocoding API. MapboxGeocoder.swift exposes the power of theCarmen geocoder through a simple API similar to Core Location’s CLGeocoder.
Note that use of the Geocoding API via MapboxGeocoder.swift is billed by API requests. For more information, see theGeocoding API pricing documentation.
MapboxGeocoder.swift pairs well withMapbox Directions for Swift,MapboxStatic.swift, and theMapbox Maps SDK for iOS or theMapbox Maps SDK for macOS.
Specify the following dependency in yourCarthage Cartfile:
github "mapbox/MapboxGeocoder.swift" ~> 0.15Or in yourCocoaPods Podfile:
pod'MapboxGeocoder.swift','~> 0.15'
Or in yourSwift Package Manager Package.swift:
.package(url:"https://github.com/mapbox/MapboxGeocoder.swift.git", from:"0.15.0")
Thenimport MapboxGeocoder or@import MapboxGeocoder;.
For Objective-C targets, it may be necessary to enable theALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES build setting.
This repository includes example applications written in both Swift and Objective-C showing use of the framework (as well as a comparison of writing apps in either language). TheMapbox API Documentation explains the underlying HTTP request and response format, as well asrelevant limits that also apply when using this library.
- One of the following package managers:
- CocoaPods 1.10 or above
- Carthage 0.38 or above
- Swift Package Manager 5.3 or above
- Xcode 12 or above
- One of the following operating systems:
- iOS 12.0 or above
- macOS 10.14 or above
- tvOS 12.0 or above
- watchOS 5.0 or above
You will need aMapbox access token in order to use the API. If you’re already using theMapbox Maps SDK for iOS orMapbox Maps SDK for macOS, MapboxGeocoder.swift automatically recognizes your access token, as long as you’ve placed it in theMGLMapboxAccessToken key of your application’s Info.plist file.
The examples below are each provided in Swift (denoted withmain.swift) and Objective-C (main.m). For further details about each class and method, use the Quick Help feature inside Xcode.
The main geocoder class is Geocoder in Swift or MBGeocoder in Objective-C. Create a geocoder object using your access token:
// main.swiftimport MapboxGeocoderletgeocoder=Geocoder(accessToken:"<#your access token#>")
// main.m@import MapboxGeocoder;MBGeocoder *geocoder = [[MBGeocoderalloc]initWithAccessToken:@"<#your access token#>"];
Alternatively, you can place your access token in theMGLMapboxAccessToken key of your application’s Info.plist file, then use the shared geocoder object:
// main.swiftletgeocoder=Geocoder.shared
// main.mMBGeocoder *geocoder = [MBGeocodersharedGeocoder];
With the geocoder in hand, construct a geocode options object and pass it into theGeocoder.geocode(_:completionHandler:) method.
Forward geocoding takes a human-readable query, such as a place name or address, and produces any number of geographic coordinates that correspond to that query. To perform forward geocoding, use ForwardGeocodeOptions in Swift or MBForwardGeocodeOptions in Objective-C.
// main.swift#if canImport(Contacts)import Contacts#endifletoptions=ForwardGeocodeOptions(query:"200 queen street")// To refine the search, you can set various properties on the options object.options.allowedISOCountryCodes=["CA"]options.focalLocation=CLLocation(latitude:45.3, longitude:-66.1)options.allowedScopes=[.address,.pointOfInterest]lettask= geocoder.geocode(options){(placemarks, attribution, error)inguardlet placemark= placemarks?.firstelse{return}print(placemark.name) // 200 Queen Stprint(placemark.qualifiedName) // 200 Queen St, Saint John, New Brunswick E2L 2X1, Canadaletcoordinate= placemark.location.coordinateprint("\(coordinate.latitude),\(coordinate.longitude)") // 45.270093, -66.050985#if canImport(Contacts)letformatter=CNPostalAddressFormatter()print(formatter.string(from: placemark.postalAddress!)) // 200 Queen St // Saint John New Brunswick E2L 2X1 // Canada#endif}
// main.m#if !TARGET_OS_TV@import Contacts;#endifMBForwardGeocodeOptions *options = [[MBForwardGeocodeOptionsalloc]initWithQuery:@"200 queen street"];// To refine the search, you can set various properties on the options object.options.allowedISOCountryCodes = @[@"CA"];options.focalLocation = [[CLLocationalloc]initWithLatitude:45.3longitude:-66.1];options.allowedScopes = MBPlacemarkScopeAddress | MBPlacemarkScopePointOfInterest;NSURLSessionDataTask *task = [geocodergeocodeWithOptions:optionscompletionHandler:^(NSArray<MBGeocodedPlacemark *> * _Nullable placemarks,NSString * _Nullable attribution,NSError * _Nullable error) { MBPlacemark *placemark = placemarks[0];NSLog(@"%@", placemark.name);// 200 Queen StNSLog(@"%@", placemark.qualifiedName);// 200 Queen St, Saint John, New Brunswick E2L 2X1, Canada CLLocationCoordinate2D coordinate = placemark.location.coordinate;NSLog(@"%f,%f", coordinate.latitude, coordinate.longitude);// 45.270093, -66.050985#if !TARGET_OS_TV CNPostalAddressFormatter *formatter = [[CNPostalAddressFormatteralloc]init];NSLog(@"%@", [formatterstringFromPostalAddress:placemark.postalAddress]);// 200 Queen St// Saint John New Brunswick E2L 2X1// Canada#endif}];
Reverse geocoding takes a geographic coordinate and produces a hierarchy of places, often beginning with an address, that describes the coordinate’s location. To perform reverse geocoding, use ReverseGeocodeOptions in Swift or MBReverseGeocodeOptions in Objective-C.
// main.swiftletoptions=ReverseGeocodeOptions(coordinate:CLLocationCoordinate2D(latitude:40.733, longitude:-73.989))// Or perhaps: ReverseGeocodeOptions(location: locationManager.location)lettask= geocoder.geocode(options){(placemarks, attribution, error)inguardlet placemark= placemarks?.firstelse{return}print(placemark.imageName??"") // telephoneprint(placemark.genres?.joined(separator:",")??"") // computer, electronicprint(placemark.administrativeRegion?.name??"") // New Yorkprint(placemark.administrativeRegion?.code??"") // US-NYprint(placemark.place?.wikidataItemIdentifier??"") // Q60}
// main.mMBReverseGeocodeOptions *options = [[MBReverseGeocodeOptionsalloc]initWithCoordinate:CLLocationCoordinate2DMake(40.733, -73.989)];// Or perhaps: [[MBReverseGeocodeOptions alloc] initWithLocation:locationManager.location]NSURLSessionDataTask *task = [geocodergeocodeWithOptions:optionscompletionHandler:^(NSArray<MBGeocodedPlacemark *> * _Nullable placemarks,NSString * _Nullable attribution,NSError * _Nullable error) { MBPlacemark *placemark = placemarks[0];NSLog(@"%@", placemark.imageName);// telephoneNSLog(@"%@", [placemark.genrescomponentsJoinedByString:@","]);// computer, electronicNSLog(@"%@", placemark.administrativeRegion.name);// New YorkNSLog(@"%@", placemark.administrativeRegion.code);// US-NYNSLog(@"%@", placemark.place.wikidataItemIdentifier);// Q60}];
Withbatch geocoding, you can perform up to 50 distinct forward or reverse geocoding requests simultaneously and store the results in a private database. Create a ForwardBatchGeocodingOptions or ReverseBatchGeocodingOptions object in Swift, or an MBForwardBatchGeocodingOptions or MBReverseBatchGeocodingOptions object in Objective-C, and pass it into theGeocoder.batchGeocode(_:completionHandler:) method.
// main.swiftletoptions=ForwardBatchGeocodeOptions(queries:["skyline chili","gold star chili"])options.focalLocation= locationManager.locationoptions.allowedScopes=.pointOfInterestlettask= geocoder.batchGeocode(options){(placemarksByQuery, attributionsByQuery, error)inguardlet placemarksByQuery= placemarksByQueryelse{return}letnearestSkyline=placemarksByQuery[0][0].locationletdistanceToSkyline= nearestSkyline.distance(from: locationManager.location)letnearestGoldStar=placemarksByQuery[1][0].locationletdistanceToGoldStar= nearestGoldStar.distance(from: locationManager.location)letdistance=LengthFormatter().string(fromMeters:min(distanceToSkyline, distanceToGoldStar))print("Found a chili parlor\(distance) away.")}
// main.mMBForwardBatchGeocodeOptions *options = [[MBForwardBatchGeocodeOptionsalloc]initWithQueries:@[@"skyline chili",@"gold star chili"]];options.focalLocation = locationManager.location;options.allowedScopes = MBPlacemarkScopePointOfInterest;NSURLSessionDataTask *task = [geocoderbatchGeocodeWithOptions:optionscompletionHandler:^(NSArray<NSArray<MBGeocodedPlacemark *> *> * _Nullable placemarksByQuery,NSArray<NSString *> * _Nullable attributionsByQuery,NSError * _Nullable error) {if (!placemarksByQuery) {return; } MBPlacemark *nearestSkyline = placemarksByQuery[0][0].location; CLLocationDistance distanceToSkyline = [nearestSkylinedistanceFromLocation:locationManager.location]; MBPlacemark *nearestGoldStar = placemarksByQuery[1][0].location; CLLocationDistance distanceToGoldStar = [nearestGoldStardistanceFromLocation:locationManager.location];NSString *distance = [NSLengthFormatterstringFromMeters:MIN(distanceToSkyline, distanceToGoldStar)];NSLog(@"Found a chili parlor%@ away.", distance);}];
Batch geocoding is available to Mapbox enterprise accounts. See theMapbox Geocoding website for more information.
To run the included unit tests, you need to useCarthage 0.19 or above to install the dependencies.
carthage bootstrapopen MapboxGeocoder.xcodeproj- Switch to the “MapboxGeocoder iOS” scheme and go to Product ‣ Test.
Alternatively, open Package.swift in Xcode and go to Product ‣ Test, or runswift test on the command line.
About
Address search and reverse geocoding in Swift or Objective-C on iOS, macOS, tvOS, and watchOS
Topics
Resources
License
Code of conduct
Contributing
Security policy
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.
Contributors15
Uh oh!
There was an error while loading.Please reload this page.