如何通过坐标(swift)指定marker.title?

时间:2016-08-22 14:47:56

标签: ios swift google-maps-sdk-ios

我有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


}

我找不到那个好的解决方案

2 个答案:

答案 0 :(得分:1)

获取这样的地址: -

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

    }


}

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

答案 1 :(得分:0)

您需要对坐标进行地理编码。您每分钟可以执行50次限制(由谷歌设置),因此使用这样做是有效的。 Here is a tutorial on the process

获得地址后,您只需说出

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

根据需要对其进行格式化。另外,我不明白为什么你会在该函数中包含代码行self.googleMapsView.myLocationEnabled = false。它可能应该去其他地方,但我会允许怀疑它的位置。