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

后端 未结 5 1407
我在风中等你
我在风中等你 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:55

    Here's my solution for this problem. Building a GMSCoordinateBounds object by multiple coordinates.

    - (void)focusMapToShowAllMarkers
    {       
        CLLocationCoordinate2D myLocation = ((GMSMarker *)_markers.firstObject).position;
        GMSCoordinateBounds *bounds = [[GMSCoordinateBounds alloc] initWithCoordinate:myLocation coordinate:myLocation];
    
        for (GMSMarker *marker in _markers)
            bounds = [bounds includingCoordinate:marker.position];
    
        [_mapView animateWithCameraUpdate:[GMSCameraUpdate fitBounds:bounds withPadding:15.0f]];
    }
    

    Updated answer: Since GMSMapView markers property is deprecated, you should save all markers in your own array.

    updated swift 3 answer:

        func focusMapToShowAllMarkers() {
            let firstLocation = (markers.first as GMSMarker).position
            var bounds = GMSCoordinateBoundsWithCoordinate(firstLocation, coordinate: firstLocation)
    
            for marker in markers {
                bounds = bounds.includingCoordinate(marker.position)
            }
            let update = GMSCameraUpdate.fitBounds(bounds, withPadding: CGFloat(15))
            self.mapView.animate(cameraUpdate: update)
      }
    

提交回复
热议问题