如何找到地址的坐标?

How do I find the coordinates of a address?

我正在制作一个应用程序,它使用 MapKit 在地址的坐标上放置一个点。

我已经制作了 class,并且在 class 中设置了我的所有功能。

我需要能够 return "getLocation()" 这将是地址的字符串,并将该字符串与 CLGeoCoder().geocodeAdressString 一起使用并获取坐标。

这是我的 classes

import UIKit

class Vendor {

    private var name = String()
    private var type = String()
    private var location = String()
    private var logo = UIImage()

    required init(name: String, type: String) {
        self.name = name
        self.type = type
        self.location = ""
        self.logo = UIImage()
    }


    func getName() -> String {
        return self.name
    }
    func setName(name: String) {
        self.name = name
    }


    func getType() -> String {
        return self.type
    }
    func setType(type: String) {
        self.type = type
    }

    func getLocation() -> String {
        return self.location
    }
    func setLocation(address: String) {
        self.location = address
    }

    func getLogo() -> UIImage {
        return self.logo
    }
    func setLogo(image: UIImage) {
        self.logo = image
    }

}

假设供应商中的位置 class 是供应商所在的街道、城市和国家/地区,您的代码可能如下所示:

    func geoCodeVendor() {

    let vendorLocation = myVendor.getLocation
    let geocoder = CLGeocoder()
    geocoder.geocodeAddressString(vendorLocation) { (placemarks, error) in

        self.centerCoordinate = (placemarks?.first?.location?.coordinate)!
        //Whather more you want to do in this completion handler.

    }
}

在这里,您在 class 中创建了一个 Vendor 实例 myVendor,您正在对您的供应商进行地理编码。在那个 class 你已经创建了一个 属性 centerCoordinate = CLLocationCoordinate2D().

通常,您有一个供应商 class,其名称、地址和城市位于不同的属性中。例如:

class Vendor {

    private var name = String()
    private var type = String()
    private var address = String()
    private var city = String()
    private var logo = UIImage()
}

然后在 getLocation 函数中附加地址和城市。请注意,当地址尽可能完整时,地理编码会更准确,即地址(包含数字、城市、国家/地区。

希望对您有所帮助。