Swift GoogleMaps fitBounds Zoom

时间:2017-10-06 14:05:55

标签: swift google-maps zoom markers fitbounds

新编码器尝试在我的视图中使用GoogleMap。

我已经搜索了很多信息,但我得出了这个结论,但它对我不起作用。

覆盖func loadView(){

    var markerList = [GMSMarker]()

    // Create a GMSCameraPosition
    let camera = GMSCameraPosition.camera(withLatitude: 4.390205, longitude: 2.154007, zoom: 8)
    let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
    mapView.isMyLocationEnabled = true
    view = mapView

    mapView.settings.myLocationButton = true
    //mapView.setMinZoom(10, maxZoom: 20)

    //create markers
    for loc in arrayOfMapStops {
        let marker = GMSMarker()
        marker.position = CLLocationCoordinate2D(latitude: loc.lat, longitude: loc.long)
        marker.title = loc.address
        marker.snippet = loc.type
        if loc.type == "Entrega" {marker.icon = GMSMarker.markerImage(with: .green)}
        else {marker.icon = GMSMarker.markerImage(with: .blue)}
        marker.map = mapView
        markerList.append(marker)
    }

    //fit map to markers
    var bounds = GMSCoordinateBounds()
    for marker in markerList {
        bounds = bounds.includingCoordinate(marker.position)
    }
    let update = GMSCameraUpdate.fit(bounds)
    mapView.moveCamera(update)
}

未使用适当的缩放调整地图。

image of situation

任何人都可以帮我解决缩放问题?

提前致谢:)

1 个答案:

答案 0 :(得分:2)

我自己解决了这个问题。我使用DispatchQueue将缩放设置为我的地图。

这是我的最终代码:

override func loadView() {

    var markerList = [GMSMarker]()

    // Create a GMSCameraPosition
    let camera = GMSCameraPosition.camera(withLatitude: 40.4167 , longitude: -3.70325, zoom: 8)
    let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
    mapView.isMyLocationEnabled = true
    view = mapView

    mapView.settings.myLocationButton = true
    //mapView.setMinZoom(10, maxZoom: 20)

    //create markers
    for loc in arrayOfMapStops {
        let marker = GMSMarker()
        marker.position = CLLocationCoordinate2D(latitude: loc.lat, longitude: loc.long)
        marker.title = loc.address
        marker.snippet = loc.type
        if loc.type == "Entrega" {marker.icon = GMSMarker.markerImage(with: .green)}
        else {marker.icon = GMSMarker.markerImage(with: .blue)}
        marker.map = mapView
        markerList.append(marker)
    }

    delay(seconds: 3) { () -> () in
        //fit map to markers
        var bounds = GMSCoordinateBounds()
        for marker in markerList {
            bounds = bounds.includingCoordinate(marker.position)
        }
        let update = GMSCameraUpdate.fit(bounds, withPadding: 100.0)
        mapView.animate(with: update)
    }
}

func delay(seconds: Double, completion:@escaping ()->()) {
    let when = DispatchTime.now() + seconds
    DispatchQueue.main.asyncAfter(deadline: when) {
        completion()
    }
}

:)