单击swift显示标记地址(street-Address)

时间:2016-06-14 06:19:23

标签: swift google-maps marker street-address

我在谷歌地图中有一个标记的纬度和经度位置,我想将其转换为Swift中的位置名称String。做这个的最好方式是什么? 我想展示标记'地址,我不知道该怎么做。

这是我用来添加标记并获取纬度和经度的代码:

func mapView(mapView: GMSMapView, didLongPressAtCoordinate coordinate: CLLocationCoordinate2D) {
        if counterMarker < 2
        {
            counterMarker += 1
            let marker = GMSMarker(position: coordinate)
            marker.appearAnimation = kGMSMarkerAnimationPop

              marker.map = mapView
            marker.position.latitude = coordinate.latitude
            marker.position.longitude = coordinate.longitude

            print(marker.position.latitude)
            print(marker.position.longitude)


            }
    }

1 个答案:

答案 0 :(得分:2)

    func mapView(mapView: GMSMapView, didLongPressAtCoordinate coordinate: CLLocationCoordinate2D) {
            if counterMarker < 2
            {
                counterMarker += 1
                let marker = GMSMarker(position: coordinate)
                marker.appearAnimation = kGMSMarkerAnimationPop

                  marker.map = mapView
                marker.position.latitude = coordinate.latitude
                marker.position.longitude = coordinate.longitude

                   self.getAddressForLatLng(String(format: "%@",marker.position.latitude), longitude:String(format: "%@",marker.position.longitude)

                }
        }


  func getAddressForLatLng(latitude: String, longitude: String) {
        let url = NSURL(string: "https://maps.googleapis.com/maps/api/geocode/json?latlng=\(latitude),\(longitude)&key=YOUR-APIKEY")
        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("\n\(number) \(street), \(city), \(state) \(zip) \(address)")
            }
        }
    }