1 google-maps bounds ios swift
我的谷歌地图上有几个标记如何适合他们的相机?
这是我的代码:
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()
Run Code Online (Sandbox Code Playgroud)
首先,您需要创建一个数组来保存标记列表
var markerList = [GMSMarker]()
Run Code Online (Sandbox Code Playgroud)
然后你可以打电话animateWithCameraUpdate(GMSCameraUpdate.fitBounds(bounds))调整你的相机:
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))
}
Run Code Online (Sandbox Code Playgroud)
你可以在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()
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3412 次 |
| 最近记录: |