Milad Aghamohammadi
Milad Aghamohammadi

Reputation: 1976

swift - how to fit GMSMapView (google map) to show all markers and prevent over zoom

One of my colleagues is working with google map on ios-swift and she wants show some markers to map and fit map zoom in first time to show all markers only. The main problem occur when the markers are so close together and map zoom to level 18 or 19 and it's too much. She want prevent this situation and in this case, set map zoom to level 15, but after showing, user can zoom in to markers if the user wants. We know can fit map to markers with snippet below

var bounds = GMSCoordinateBounds()
for location in locationArray
{
    let latitude = location.valueForKey("latitude")
    let longitude = location.valueForKey("longitude")

    let marker = GMSMarker()
    marker.position = CLLocationCoordinate2D(latitude:latitude, longitude:longitude)
    marker.map = self.mapView
    bounds = bounds.includingCoordinate(marker.position)
}
let update = GMSCameraUpdate.fit(bounds, withPadding: 50)
mapView.animate(update)

but we don't found any zoom control on fitBounds or animateWithCameraUpdate

Upvotes: 8

Views: 4622

Answers (1)

Milad Aghamohammadi
Milad Aghamohammadi

Reputation: 1976

I found a simple trick to solve the problem. You can use setMinZoom before fit and animate to prevent over zoom and then setMinZoom again to allow user zoom.

var bounds = GMSCoordinateBounds()
for location in locationArray
{
    let latitude = location.valueForKey("latitude")
    let longitude = location.valueForKey("longitude")

    let marker = GMSMarker()
    marker.position = CLLocationCoordinate2D(latitude:latitude, longitude:longitude)
    marker.map = self.mapView
    bounds = bounds.includingCoordinate(marker.position)
}

mapView.setMinZoom(1, maxZoom: 15)//prevent to over zoom on fit and animate if bounds be too small

let update = GMSCameraUpdate.fit(bounds, withPadding: 50)
mapView.animate(update)

mapView.setMinZoom(1, maxZoom: 20) // allow the user zoom in more than level 15 again

Upvotes: 15

Related Questions