How to draw routes between two locations in google maps iOS swift

前端 未结 5 1067
北海茫月
北海茫月 2021-02-04 13:31

I\'m using google maps in my iOS swift project. I want to draw a path between two locations on the map (Not straight line). Any idea how to do that ?

5条回答
  •  逝去的感伤
    2021-02-04 13:58

    Above all answers can draw routes but there is a way that you can draw accurate route using directions API.Here is the code hopefully it will help for you.

    func getRouteSteps(from source: CLLocationCoordinate2D, to destination: CLLocationCoordinate2D) {
    
        let session = URLSession.shared
    
        let url = URL(string: "https://maps.googleapis.com/maps/api/directions/json?origin=\(source.latitude),\(source.longitude)&destination=\(destination.latitude),\(destination.longitude)&sensor=false&mode=driving&key=\(Your_API_Key)")!
    
        let task = session.dataTask(with: url, completionHandler: {
            (data, response, error) in
    
            guard error == nil else {
                print(error!.localizedDescription)
                return
            }
    
            guard let jsonResult = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any] else {
    
                print("error in JSONSerialization")
                return
    
            }
    
    
    
            guard let routes = jsonResult["routes"] as? [Any] else {
                return
            }
    
            guard let route = routes[0] as? [String: Any] else {
                return
            }
    
            guard let legs = route["legs"] as? [Any] else {
                return
            }
    
            guard let leg = legs[0] as? [String: Any] else {
                return
            }
    
            guard let steps = leg["steps"] as? [Any] else {
                return
            }
              for item in steps {
    
                guard let step = item as? [String: Any] else {
                    return
                }
    
                guard let polyline = step["polyline"] as? [String: Any] else {
                    return
                }
    
                guard let polyLineString = polyline["points"] as? String else {
                    return
                }
    
                //Call this method to draw path on map
                DispatchQueue.main.async {
                    self.drawPath(from: polyLineString)
                }
    
            }
        })
        task.resume()
    }
    

    And then

        //MARK:- Draw Path line
    func drawPath(from polyStr: String){
        let path = GMSPath(fromEncodedPath: polyStr)
        let polyline = GMSPolyline(path: path)
        polyline.strokeWidth = 3.0
        polyline.map = mapView // Google MapView
    
    
        let cameraUpdate = GMSCameraUpdate.fit(GMSCoordinateBounds(coordinate: sourceLocationCordinates, coordinate: destinationLocationCordinates))
        mapView.moveCamera(cameraUpdate)
        let currentZoom = mapView.camera.zoom
        mapView.animate(toZoom: currentZoom - 1.4)
    }
    

    Note: I have added sourcesLocationCordinates and destinationLocationCordinates variables.Don't forget to replace them with your source and destination.Hopefully this will help you making perfect route line.

提交回复
热议问题