问题描述:

I have a couple of markers on my google map how to fit camera to them ?

here is my code:

NSURLSession.sharedSession().dataTaskWithURL(

NSURL(string: url)!)

{ data, response, error in

do {

let jsonData = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers ) as! NSDictionary

for (var i=0; i < jsonData.allKeys.count; i++){

var key = jsonData.allKeys[i] as! String

var id = jsonData[key] as! NSDictionary

var club = id["club"] as! NSDictionary

var location = club["location"] as! NSDictionary

var latitude = location["latitude"] as! Double

var longitude = location["longitude"] as! Double

dispatch_async(dispatch_get_main_queue()) {

let position: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)

let marker = GMSMarker(position: position)

marker.title = club["name"] as! String

marker.map = self.map

}

}

} catch {

// report error

}

}.resume()

网友答案:

First you need to make an array to hold your list of markers

var markerList = [GMSMarker]()

Then you can call animateWithCameraUpdate(GMSCameraUpdate.fitBounds(bounds)) to adjust your camera:

func fitAllMarkers() {
    var bounds = GMSCoordinateBounds()

    for marker in markerList {
        bounds = bounds.includingCoordinate(marker.position)
    }

    map.animateWithCameraUpdate(GMSCameraUpdate.fitBounds(bounds))
}

Can you call this in your dispatch_async closure:

 dispatch_async(dispatch_get_main_queue()) {
       let position: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
       let marker = GMSMarker(position: position)
       marker.title = club["name"] as! String
       marker.map = self.map

      //new code
      self.markerList.append(marker)
      self.fitAllMarkers()
   }
相关阅读:
Top