2016-06-14 83 views
0

我想要在Swift中将位置名称字符串转换为谷歌地图中的标记经度和纬度位置。做这个的最好方式是什么? 我想显示标记的位置地址,我不知道该怎么做。用swift点击显示标记地址(街道地址)

这里是我的代码,我用来添加标记,并得到纬度和经度:

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) 


      } 
    } 
+0

的可能重复: http://stackoverflow.com/questions/19025148/ios-7- add-overlay-crash-app/http://stackoverflow.com/questions/6721124/app-crashing-when-i-add-overlay-to-mkmapview/ http://stackoverflow.com/questions/31390630/exc-使用gmaps-sdk-1-9-0-xcode-6-4-runing-on-8-3-device/http://stackoverflow.com/questions/31264537/adding-google-maps- as-subview-crashes-ios-app-with-exc-bad/http://stackoverflow.com/questions/24837295/how-to-solve-this-exc-bad-accesscode-exc-i38 6-gpflt-in-swift-programming –

回答

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

我有这个错误:'sendSynchronousRequest(_:returningResponse :)'在iOS 9.0中已弃用:使用[NSURLSession dataTaskWithRequest:completionHandler:](请参阅NSURLSession.h!并且我在我的应用程序中看不到任何地址 –

+0

使用此代码我添加了一次 –

+0

现在它无法再生成任何标记! (字符串格式:“%@”,marker.position.latitude),经度:字符串(格式:“%@”,marker.position.longitude)) –