I am having a bit of trouble understanding Apple's MapKit in Swift 3.
I found an example here: How to open maps App programmatically with coordinates in swift?
public func openMapForPlace(lat:Double = 0, long:Double = 0, placeName:String = "") {
let latitude: CLLocationDegrees = lat
let longitude: CLLocationDegrees = long
let regionDistance:CLLocationDistance = 100
let coordinates = CLLocationCoordinate2DMake(latitude, longitude)
let regionSpan = MKCoordinateRegionMakeWithDistance(coordinates, regionDistance, regionDistance)
let options = [
MKLaunchOptionsMapCenterKey: NSValue(mkCoordinate: regionSpan.center),
MKLaunchOptionsMapSpanKey: NSValue(mkCoordinateSpan: regionSpan.span)
]
let placemark = MKPlacemark(coordinate: coordinates, addressDictionary: nil)
let mapItem = MKMapItem(placemark: placemark)
mapItem.name = placeName
mapItem.openInMaps(launchOptions: options)
}
This works absolutely swimmingly, except that I need to use an address instead of coordinates in this case.
I have found methods for doing this using google maps, but I cant seem to find a specific answer for Apple Maps, if it exists, I've completed glazed over it.
If anyone can help me to understand what the correct approach is, that would be amazing. I'm using:
You need to use the Geocoding service to convert an address to the corresponding geolocation.
For instance, add this function to your toolkit:
func coordinates(forAddress address: String, completion: @escaping (CLLocationCoordinate2D?) -> Void) {
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(address) {
(placemarks, error) in
guard error == nil else {
print("Geocoding error: \(error!)")
completion(nil)
return
}
completion(placemarks.first?.location?.coordinate)
}
}
and then use it like this:
coordinates(forAddress: "YOUR ADDRESS") {
(location) in
guard let location = location else {
// Handle error here.
return
}
openMapForPlace(lat: location.latitude, long: location.longitude)
}
You need to use geoCode to get the coordinates from the address... This should work:
let geocoder = CLGeocoder()
geocoder.geocodeAddressString("ADDRESS_STRING") { (placemarks, error) in
if error != nil {
//Deal with error here
} else if let placemarks = placemarks {
if let coordinate = placemarks.first?.location?.coordinate {
//Here's your coordinate
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With