How can I plot addresses in Swift, converting addr

2019-02-01 00:51发布

问题:

In Objective-C this code works fine to plot an address and it finds the longitude and latitude coordinates:

     NSString *address = @"1 Infinite Loop, CA, USA";
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder geocodeAddressString:address 
             completionHandler:^(NSArray* placemarks, NSError* error){
                 // Check for returned placemarks
                 if (placemarks && placemarks.count > 0) {
                     CLPlacemark *topResult = [placemarks objectAtIndex:0];
                     // Create a MLPlacemark and add it to the map view
                     MKPlacemark *placemark = [[MKPlacemark alloc] initWithPlacemark:topResult];
                     [self.mapView addAnnotation:placemark];
                     [placemark release];
                 }
                 [geocoder release];
             }];

I have been searching for days on how to do this with Swift?! Could anyone point me in the right direction? Could you explain if a user needs an internet connection for this to work. Sorry if these questions sounds a bit basic, but I am quite new to this and learning every day.

I understand that I have to use this code, but cannot find a way to implement it

func geocodeAddressString(_ addressString: String!,
    completionHandler completionHandler: CLGeocodeCompletionHandler!)

回答1:

Try something like

var address = "1 Infinite Loop, CA, USA"
var geocoder = CLGeocoder()
geocoder.geocodeAddressString(address, {(placemarks: [AnyObject]!, error: NSError!) -> Void in
    if let placemark = placemarks?[0] as? CLPlacemark {
        self.mapView.addAnnotation(MKPlacemark(placemark: placemark))
    }
})


回答2:

XCode 9 & Swift 3:

import CoreLocation

let address = "1 Infinite Loop, CA, USA"
let geocoder = CLGeocoder()

geocoder.geocodeAddressString(address, completionHandler: {(placemarks, error) -> Void in
   if((error) != nil){
      print("Error", error)
   }
   if let placemark = placemarks?.first {
      let coordinates:CLLocationCoordinate2D = placemark.location!.coordinate
      }
    })


回答3:

var address = "1 Infinite Loop, CA, USA"
var geocoder = CLGeocoder()    

geocoder.geocodeAddressString(address) {
    if let placemarks = $0 {
       println(placemarks)
    } else {
       println($1)
    }
}