2016-08-22 99 views
-1

我有longitudelatitude,因爲我使用didLongPressAtCoordinate,現在我想將marker.title分配給這個coordinate的標題。如何通過座標(swift)分配marker.title?

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 


} 

我無法找到該

+4

嘿scbas1000,歡迎來到Stack Overflow。你的問題非常模糊,幾乎沒有機會被回答。請訪問[如何問]的指南(http://stackoverflow.com/help/how-to-ask)。 – Alexander

+0

感謝您的關注,我編輯它,現在是對的我認爲 – scbas1000

+1

@ scbas1000不,你的問題仍然很模糊,你還沒有發佈任何代碼,顯示你到目前爲止。發佈你的代碼,明確地討論你在一分鐘內的工作,你試圖達到的目標(例子會有所幫助),然後列出你在面對的錯誤/問題 –

回答

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

    } 


} 

記住: - 的baseUrlserverKey是你的谷歌控制檯的baseUrl和serverKey

+0

你應該認識到,州和城市不會經常出現,而且你的代碼經常出錯。最重要的是,它的寫作嚴格要與美國的大多數人一起工作,並且不會在大多數美國人以外工作。 – Sethmr

+0

感謝您的回覆#Davavidian – scbas1000

0

您需要進行地理編碼的座標很好的解決方案。你有50次的限制,你可以每分鐘做一次(由谷歌設置),所以要高效使用這樣做。 Here is a tutorial on the process

一旦你的地址,你剛纔說

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

格式你想要的東西。此外,我不明白爲什麼你會在該函數內部有一行代碼self.googleMapsView.myLocationEnabled = false。它可能應該去其他地方,但我會允許對其位置的懷疑的好處。