Show marker address (street-Address) with clicking in swift

断了今生、忘了曾经 提交于 2020-01-17 07:19:08

问题


I have a latitude and longitude location of marker in google maps that I want to convert to the location name String in Swift. What is the best way to do this? i want to show markers' location address and i don't know how to do it .

here is my code that i used to add marker and get latitude and longitude:

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:


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


来源:https://stackoverflow.com/questions/37804311/show-marker-address-street-address-with-clicking-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!