google ios SDK swift fit bounds

时间:2015-08-26 17:12:08

标签: ios swift google-maps bounds

我的谷歌地图上有几个标记如何适合相机?

这是我的代码:

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

2 个答案:

答案 0 :(得分:8)

首先,您需要创建一个数组来保存标记列表

var markerList = [GMSMarker]()

然后你可以拨打animateWithCameraUpdate(GMSCameraUpdate.fitBounds(bounds))来调整你的相机:

func fitAllMarkers() {
    var bounds = GMSCoordinateBounds()

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

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

您可以在dispatch_async关闭中调用此内容:

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

答案 1 :(得分:2)

在SWIFT 3.1群集中点击:

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