Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift, Google map fit bound for all the markers

I want to fit all the markers in the google map window with auto zoom.

Below is my code

func loadGoogleMap()
{

    dispatch_async(dispatch_get_main_queue(),
        {
            self.googleMapView.clear()

            self.googleMapView.delegate = self
            var visibleRegion : GMSVisibleRegion = self.googleMapView.projection.visibleRegion()
            var bounds = GMSCoordinateBounds(coordinate: visibleRegion.nearLeft, coordinate: visibleRegion.nearRight)
            var count = 1
            for Prop: Property in self.properties
            {
                if Prop.propLat != ""
                {

                   //  println("lat >>  \(Prop.propLat) lang >> \(Prop.propLang)")
                    var latStr = Prop.propLat
                    var latDbl : Double  = Double(latStr.floatValue)
                    var langStr = Prop.propLang as NSString
                    var langDbl : Double = Double(langStr.floatValue)
                    var marker = GMSMarker()

                    if count == 0
                    {
  //                           let initialLocation =   CLLocationCoordinate2DMake(langDbl,latDbl)
   //                            let initialDirection = CLLocationDirection()
    //                            
    //                            let camera = GMSCameraPosition.cameraWithTarget(initialLocation, zoom: 5)
    //                            self.googleMapView.camera = camera
    //                            
                    }

                    marker.position = CLLocationCoordinate2DMake(langDbl,latDbl)
                    marker.appearAnimation = kGMSMarkerAnimationPop
                    marker.icon = UIImage(named: "red_\(Prop.propSequence)")
                    marker.title = Prop.propBuildingName as String
                    marker.snippet = Prop.propCode as String
                    marker.infoWindowAnchor = CGPointMake(0.44, 0.45);
                    bounds.includingCoordinate(marker.position)
                    marker.map = self.googleMapView
                    count++

                }

            }

            self.googleMapView.animateWithCameraUpdate(GMSCameraUpdate.fitBounds(bounds, withPadding: 30.0))

    })

   }

Above swift code is added on view willappear and viewdidload method as well. Can someone please help me what i am doing wrong in the above code.

like image 517
dhaval shah Avatar asked Aug 13 '15 07:08

dhaval shah


1 Answers

@IBOutlet weak var viewMap: GMSMapView!
var markers = [GMSMarker]()
var bounds = GMSCoordinateBounds()
    for marker in self.markers {
        bounds = bounds.includingCoordinate(marker.position)
    }
    viewMap.animate(with: GMSCameraUpdate.fit(bounds, with: UIEdgeInsetsMake(50.0 , 50.0 ,50.0 ,50.0)))
like image 156
urvashi bhagat Avatar answered Oct 05 '22 08:10

urvashi bhagat