如何通过坐标(swift)分配marker.title?

How to assign marker.title by coordinate (swift)?

我有 longitudelatitude,因为我使用 didLongPressAtCoordinate,现在我想将 marker.title 分配给此 coordinate 的标题。

func mapView(mapView: GMSMapView!, didLongPressAtCoordinate coordinate: CLLocationCoordinate2D) {

    let marker = GMSMarker()
    marker.position = CLLocationCoordinate2D(latitude: coordinate.latitude, longitude: coordinate.longitude)
    self.googleMapsView.clear()
    self.googleMapsView.myLocationEnabled = false
    marker.map = self.googleMapsView
    marker.title = --> //my problem


}

我找不到好的解决方案

您需要对坐标进行地理编码。您每分钟可以执行此操作的次数限制为 50 次(由 google 设置),因此请务必高效地执行此操作。 Here is a tutorial on the process

一旦你有了地址,你就说

marker.title = "\(theAddressVariableName)\n\nLat: \(coordinate.latitude)\nLon: coordinate.longitude"

随心所欲地格式化它。另外,我不明白为什么你会在该函数中包含代码行 self.googleMapsView.myLocationEnabled = false 。它可能应该放在其他地方,但我允许对它的位置有疑问。

像这样获取您的地址:-

  func getAddressForLatLng(latitude: CLLocationDegrees, longitude: CLLocationDegrees, completionBlock : ((addrs : String)->Void)) {
    let url = NSURL(string: "\(baseUrl)latlng=\(latitude),\(longitude)&key=\(serverKey)")
    print(url)


    let data = NSData(contentsOfURL: url!)
    let json = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! NSDictionary
    if let result = json["results"] as? NSArray {
        if let address = result[0]["address_components"] as? NSArray {
            let number = address[0]["short_name"] as! String
            let street = address[1]["short_name"] as! String
            let city = address[2]["short_name"] as! String
            let state = address[4]["short_name"] as! String
            let zip = address[6]["short_name"] as! String
            print("\(number) \(street), \(city), \(state) \(zip)")
            completionBlock(addrs: "\(number) \(street), \(city), \(state) \(zip)")

        }
    }
}

更新您的 didLongPressAtCoordinate 功能:-

func mapView(mapView: GMSMapView!, didLongPressAtCoordinate coordinate: CLLocationCoordinate2D) {

    let marker = GMSMarker()
    marker.position = CLLocationCoordinate2D(latitude: coordinate.latitude, longitude: coordinate.longitude)
    self.googleMapsView.clear()
    self.googleMapsView.myLocationEnabled = false
    marker.map = self.googleMapsView
    getAddressForLatLng(coordinate.latitude, longitude: coordinate.longitude) { (addrs) in

        marker.title = addrs
        marker.snippet = "\(coordinate.latitude),\(coordinate.longitude)"

    }


}

请注意:- baseUrlserverKey 是您的 Google 控制台 baseUrl 和 serverKey