Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 276
Milad Aghamohammadi Avatar asked Nov 18 '18 06:11

Milad Aghamohammadi


1 Answers

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
like image 137
Milad Aghamohammadi Avatar answered Nov 11 '22 06:11

Milad Aghamohammadi