dang dang - 2 months ago 14
iOS Question

Apply zoom level condition for Google Maps iOS

I have a map here:

let camera = GMSCameraPosition.cameraWithLatitude(37.0902, longitude: -95.7129, zoom: 4.0)

let mapView = GMSMapView.mapWithFrame(CGRect.zero, camera: camera)
mapView.myLocationEnabled = true
view = mapView
mapView.setMinZoom(4.6, maxZoom: 8)


I want to detect the zoom level of the user. If zoom level is more than 5, then add marker. How can it be done?

here is the code for adding marker:

let state_marker = GMSMarker()
state_marker.position = CLLocationCoordinate2D(latitude: -152.404419, longitude: 61.370716)
state_marker.title = "Test"
state_marker.snippet = "Hey, this is Test"
state_marker.map = mapView

Answer

You can use didChangeCameraPosition delegate method of GMSMapView

First, you need to extend your GMSMapView delegate in your class

class MyViewController: GMSMapViewDelegate

Then you need to assign your delegate after declaring the mapView

let camera = GMSCameraPosition.cameraWithLatitude(37.0902, longitude: -95.7129, zoom: 4.0)

let mapView = GMSMapView.mapWithFrame(CGRect.zero, camera: camera)
mapView.myLocationEnabled = true
mapView.delegate = self
view = mapView
mapView.setMinZoom(4.6, maxZoom: 8)

You can then use the didChangeCameraPosition delegate method

func mapView(mapView: GMSMapView!, didChangeCameraPosition position: GMSCameraPosition!) { 
    if(mapView.camera.zoom > 5)
      //do your code here
    }
}

You can refer the following link to get a better idea on delegate methods of GMSMapView https://developers.google.com/maps/documentation/ios-sdk/reference/protocol_g_m_s_map_view_delegate-p

Comments