search for a place and return the latitude and longitude in swift

To search for a place and return its latitude and longitude in Swift, we can use Apple's MapKit framework and its CLGeocoder class.

First, we need to import the MapKit framework into our project:

main.swift
import MapKit
14 chars
2 lines

Then, we need to create an instance of the CLGeocoder class and use its geocodeAddressString method to search for the place's location:

main.swift
let geocoder = CLGeocoder()
geocoder.geocodeAddressString("New York") { (placemarks, error) in
    if let error = error {
        print("Geocoding error: \(error.localizedDescription)")
        return
    }
    
    guard let placemark = placemarks?.first else {
        print("No placemarks found.")
        return
    }
    
    let latitude = placemark.location?.coordinate.latitude ?? 0.0
    let longitude = placemark.location?.coordinate.longitude ?? 0.0
    
    print("Latitude: \(latitude), Longitude: \(longitude)")
}
528 chars
18 lines

In this example, we are searching for "New York" and handling possible errors that may occur during the geocoding process. If the search is successful, we are retrieving the first placemark returned by the geocoder and extracting its location's latitude and longitude coordinates.

We can replace "New York" with any other place name or address. Keep in mind that the geocoder may not always return accurate results, especially for less specific search queries.

gistlibby LogSnag