How can I plot addresses in Swift, converting address to longitude and latitude coordinates?

白昼怎懂夜的黑 提交于 2019-11-30 11:08:11

问题


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)
    }
}


来源:https://stackoverflow.com/questions/24706885/how-can-i-plot-addresses-in-swift-converting-address-to-longitude-and-latitude

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!