Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set google map zoom level according to path & markers in swift

I am trying to show path in google maps from one place to another place I am getting something like this. but I need to show like this. Which means the whole path need to show & according to path on map, the zooming level should adjust

Here is the code which I tried to draw path from API. and here in let settingCam am setting camera to adjust to one of the location

func showingPathFromPickupLocToDropLoc(dropLat: Double, dropLong: Double){

    let origin = "\(dropLat),\(dropLong)"
    let destination = "\(dropLatitude),\(dropLongitude)"

    let settingCam: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: CLLocationDegrees(dropLat), longitude: CLLocationDegrees(dropLong))
    let url = URL(string: "https://maps.googleapis.com/maps/api/directions/json?origin=\(origin)&destination=\(destination)&key=\(NEWAPI.GOOGLE_APIKEY)")
    URLSession.shared.dataTask(with: url!, completionHandler: {(data, response, error) in
        if(error != nil){
            print("error")
        }else{
            do{
                let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! [String : AnyObject]
                if json["status"] as! String == "OK"{
                    let routes = json["routes"] as! [[String:AnyObject]]
                    OperationQueue.main.addOperation({
                        for route in routes{
                            let routeOverviewPolyline = route["overview_polyline"] as! [String:String]
                            let points = routeOverviewPolyline["points"]
                            let path = GMSPath.init(fromEncodedPath: points!)
                            self.PathFromPickupLocToDropLoc = GMSPolyline(path: path)
                            self.PathFromPickupLocToDropLoc.strokeColor = .gray
                            self.PathFromPickupLocToDropLoc.strokeWidth = 3.0
                            self.PathFromPickupLocToDropLoc.map = self.mapView

                            let camera = GMSCameraPosition.camera(withTarget: settingCam, zoom: 16.0)
                            self.mapView.animate(toLocation: settingCam)
                            self.mapView.animate(to: camera)
                            self.insertingMarkersFromPickupLocToDropLoc(dropLat: dropLat, dropLong: dropLong)
                        }
                    })
                }
            }catch let error as NSError{
                print(error)
            }
        }
    }).resume()
}
like image 775
Bhanuteja Avatar asked Nov 28 '22 13:11

Bhanuteja


1 Answers

You need to do like this

DispatchQueue.main.async
{
 if self.googleMap != nil
 {
  let bounds = GMSCoordinateBounds(path: path!)
  self.googleMap!.animate(with: GMSCameraUpdate.fit(bounds, withPadding: 50.0))   
 }
}
like image 134
Mitesh jadav Avatar answered Dec 10 '22 06:12

Mitesh jadav