scbas1000 scbas1000 - 3 months ago 13
iOS Question

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

I have

longitude
and
latitude
because I use
didLongPressAtCoordinate
and for now I want to assign
marker.title
to title of this
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


}


i can't find good solution for that

Answer

Get your address like this :-

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

        }
    }
}

Update your didLongPressAtCoordinate function :-

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

    }


}

Mind that :- baseUrl And serverKey are your Google console baseUrl and serverKey

Comments