从地址获取坐标并在MKMapView中显示

时间:2018-11-11 04:28:28

标签: ios swift annotations mkmapview geocoder

此应用程序的要求是最终用户需要能够从一系列位置中进行选择。我可以使用lat/long coordinates根据所选位置获取GeocodeAddressString,但是在mapView中显示所选位置坐标时遇到了困难。非常感谢您的帮助。

fileprivate func updateFields(){
    if locationArray?.count > 0
    {
        let location = locationArray![selectedLocationIndex!]
        name.text = location.name
        street.text = location.street
        city.text = location.city
        stateProvince.text = location.stateProvince
        zipPostal.text = location.zipPostal
        country.text = location.country
        phone.text = location.phone

        guard let country = country.text else { return }
        guard let street = street.text else { return }
        guard let city = city.text else { return }
        guard let state = stateProvince.text else { return }
        guard let zipPostal = zipPostal.text else { return }

        // Create Address String

        let address = ("\(country), \(street), \(city), \(state), \(zipPostal)")

        // Geocode Address String
        geocoder.geocodeAddressString(address) { (placemarks, error) in
            // Process Response
            self.processResponse(withPlacemarks: placemarks, error: error)
        }
    }
}

private func processResponse(withPlacemarks placemarks: [CLPlacemark]?, error: Error?) {
    // Update View
    if let error = error {
        print("Unable to Forward Geocode Address (\(error))")
        locationLabel.text = "Unable to Find Location for Address"
    } else {
        var location: CLLocation?
        if let placemarks = placemarks, placemarks.count > 0 {
            location = placemarks.first?.location
        }

        if let location = location {
            let coordinate = location.coordinate
            locationLabel.text = "\(coordinate.latitude), \(coordinate.longitude)"
        } else {
            locationLabel.text = "No Matching Location Found"
        }
    }
}

图像显示了具有位置信息和位置经度/纬度的位置数组

Image shows location array with location information and location longitude/latitude

我尝试了几件事,但未能成功

0 个答案:

没有答案