How to fit bounds for coordinate array with google maps sdk for iOS?

后端 未结 5 1427
我在风中等你
我在风中等你 2021-01-31 17:23

How to fit bounds for coordinate array with google maps sdk for iOS? I need to zoom map for 4 visible markers.

5条回答
  •  终归单人心
    2021-01-31 17:34

    Swift 3.0 version of Lirik's answer:

    func focusMapToShowAllMarkers() {
        let myLocation: CLLocationCoordinate2D = self.markers.first!.position
        var bounds: GMSCoordinateBounds = GMSCoordinateBounds(coordinate: myLocation, coordinate: myLocation)
    
        for marker in self.markers {
            bounds = bounds.includingCoordinate(marker.position)
            self.mapView.animate(with: GMSCameraUpdate.fit(bounds, withPadding: 15.0))
        }
    }
    

    And here's my own way:

    func focusMapToShowMarkers(markers: [GMSMarker]) {
    
        guard let currentUserLocation = self.locationManager.location?.coordinate else {
            return
        }
    
        var bounds: GMSCoordinateBounds = GMSCoordinateBounds(coordinate: currentUserLocation,
                                                              coordinate: currentUserLocation)
    
        _ = markers.map {
            bounds = bounds.includingCoordinate($0.position)
            self.mapView.animate(with: GMSCameraUpdate.fit(bounds, withPadding: 15.0))
        }
    }
    

    And you can call my function above like so:

    self.focusMapToShowMarkers(markers: [self.myLocationMarker, currentPokemonMarker])

提交回复
热议问题