Jan Milev
Jan Milev

Reputation: 13

google ios SDK swift fit bounds

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

Upvotes: 1

Views: 4271

Answers (2)

ztan
ztan

Reputation: 6931

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))
    //For Swift 5 use the one below
    //self.mapView.animate(with: GMSCameraUpdate.fit(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()
   }

Upvotes: 8

Mike
Mike

Reputation: 559

In SWIFT 3.1 on cluster tap:

func clusterManager(_ clusterManager: GMUClusterManager, didTap cluster: GMUCluster) {
    var bounds = GMSCoordinateBounds()
    for marker in cluster.items {
        bounds = bounds.includingCoordinate(marker.position)
    }
    mapView.animate(with: GMSCameraUpdate.fit(bounds))
}

Upvotes: 2

Related Questions