代码之家  ›  专栏  ›  技术社区  ›  muku

谷歌地图中未显示多段线

  •  3
  • muku  · 技术社区  · 7 年前

    我想在谷歌地图上显示目的地和来源地之间的路径。我是谷歌方向api的获取路线之间的坐标,我得到的回应和设置在谷歌地图上,但并没有显示在地图上。我的代码是

    func getPolylineRoute(from source: CLLocationCoordinate2D, to destination: CLLocationCoordinate2D){
    
        let config = URLSessionConfiguration.default
        let session = URLSession(configuration: config)
    
        let url = URL(string: "https://maps.googleapis.com/maps/api/directions/json?origin=\(source.latitude),\(source.longitude)&destination=\(destination.latitude),\(destination.longitude)&sensor=true&mode=driving&key=AIzaSyAyU5txJ86b25-_l0DW-IldSKGGYqQJn3M")!
    
        let task = session.dataTask(with: url, completionHandler: {
            (data, response, error) in
    
            DispatchQueue.main.async {
    
                if error != nil {
                    print(error!.localizedDescription)
                    AppManager.dissmissHud()
                }
                else {
                    do {
                        if let json : [String:Any] = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any]{
    
                            guard let routes = json["routes"] as? NSArray else {
                                DispatchQueue.main.async {
                                    AppManager.dissmissHud()
                                }
                                return
                            }
    
                            if (routes.count > 0) {
                                let overview_polyline = routes[0] as? NSDictionary
                                let dictPolyline = overview_polyline?["overview_polyline"] as? NSDictionary
    
                                let points = dictPolyline?.object(forKey: "points") as? String
    
                                self.showPath(polyStr: points!)
    
                                DispatchQueue.main.async {
                                    AppManager.dissmissHud()
    
                                    let bounds = GMSCoordinateBounds(coordinate: source, coordinate: destination)
                                    let update = GMSCameraUpdate.fit(bounds, with: UIEdgeInsetsMake(75, 20, 20, 20))
                                    self.vwMap!.moveCamera(update)
                                }
                            }
                            else {
                                DispatchQueue.main.async {
                                    AppManager.dissmissHud()
                                }
                            }
                        }
                    }
                    catch {
                        print("error in JSONSerialization")
                        DispatchQueue.main.async {
                            AppManager.dissmissHud()
                        }
                    }
                }
            }
        })
        task.resume()
    }
    
    
    func drawPlyLineOnMap()  {
    
        let source : CLLocationCoordinate2D  =  CLLocationCoordinate2DMake(Double((model?.fromAddressLatitude)!), Double((model?.fromAddressLongtitude)!))
        let destination : CLLocationCoordinate2D  =  CLLocationCoordinate2DMake(Double((model?.toAddressLatitude)!), Double((model?.toAddressLongtitude)!))
    
        self.vwMap.clear()
        //Source pin
        let marker = GMSMarker()
        let markerImage = UIImage(named: "from_pin")!.withRenderingMode(.alwaysOriginal)
        let markerView = UIImageView(image: markerImage)
        marker.position = source
        marker.iconView = markerView
        //marker.userData = dict
        marker.map = vwMap
    
        //Destination pin
        let markerTo = GMSMarker()
        let markerImageTo = UIImage(named: "to_red_pin")!.withRenderingMode(.alwaysOriginal)
        let markerViewTo = UIImageView(image: markerImageTo)
        markerTo.position = destination
        // marker.userData = dict
        markerTo.iconView = markerViewTo
        markerTo.map = vwMap
    
        var arrAdTemp:[AddressTableModel] = []
        arrAdTemp.append(contentsOf: arrAddresses)
        arrAdTemp.removeLast()
        arrAdTemp.removeFirst()
        for obj in arrAdTemp {
            print(obj.strLatitude)
            print(obj.strLongtitude)
            let stopOver : CLLocationCoordinate2D  =  CLLocationCoordinate2DMake(obj.strLatitude, obj.strLongtitude)
            let markerStop = GMSMarker()
            let markerImageStop = UIImage(named: "to_red_pin")!.withRenderingMode(.alwaysOriginal)
            let markerViewStop = UIImageView(image: markerImageStop)
            markerStop.position = stopOver
            //marker.userData = dict
            markerStop.iconView = markerViewStop
            markerStop.map = vwMap
        }
    
        self.getPolylineRoute(from: source, to: destination)
    }
    
    func showPath(polyStr :String){
        let path = GMSPath(fromEncodedPath: polyStr)
        let polyline = GMSPolyline(path: path)
        polyline.strokeWidth = 3.0
        polyline.strokeColor = UIColor.black
        polyline.map = vwMap // Your map view
    }
    

    我尝试了下面给出的很多答案,但都不适合我。请帮帮我。

    1. 1st answer tried
    2. 2nd answer tried
    3. 3rd answer tried
    2 回复  |  直到 7 年前
        1
  •  6
  •   Vinod Kumar    7 年前

    您设置了错误的边界,因此它不会显示在地图上。我已经试过你的代码了,效果很好。请将边界区域更改为(0,0,0,0)

     func getPolylineRoute(from source: CLLocationCoordinate2D, to destination: CLLocationCoordinate2D){
    
            let config = URLSessionConfiguration.default
            let session = URLSession(configuration: config)
    
            let url = URL(string: "https://maps.googleapis.com/maps/api/directions/json?origin=\(source.latitude),\(source.longitude)&destination=\(destination.latitude),\(destination.longitude)&sensor=true&mode=driving&key=AIzaSyAyU5txJ86b25-_l0DW-IldSKGGYqQJn3M")!
    
            let task = session.dataTask(with: url, completionHandler: {
                (data, response, error) in
    
                DispatchQueue.main.async {
    
                    if error != nil {
                        print(error!.localizedDescription)
                        AppManager.dissmissHud()
                    }
                    else {
                        do {
                            if let json : [String:Any] = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any]{
    
                                guard let routes = json["routes"] as? NSArray else {
                                    DispatchQueue.main.async {
                                        AppManager.dissmissHud()
                                    }
                                    return
                                }
    
                                if (routes.count > 0) {
                                    let overview_polyline = routes[0] as? NSDictionary
                                    let dictPolyline = overview_polyline?["overview_polyline"] as? NSDictionary
    
                                    let points = dictPolyline?.object(forKey: "points") as? String
    
                                    self.showPath(polyStr: points!)
    
                                    DispatchQueue.main.async {
                                        AppManager.dissmissHud()
    
                                        let bounds = GMSCoordinateBounds(coordinate: source, coordinate: destination)
    //below bounds change as 0 check it on full screen
                                        let update = GMSCameraUpdate.fit(bounds, with: UIEdgeInsetsMake(0, 0, 0, 0))
                                        self.vwMap!.moveCamera(update)
                                    }
                                }
                                else {
                                    DispatchQueue.main.async {
                                        AppManager.dissmissHud()
                                    }
                                }
                            }
                        }
                        catch {
                            print("error in JSONSerialization")
                            DispatchQueue.main.async {
                                AppManager.dissmissHud()
                            }
                        }
                    }
                }
            })
            task.resume()
        }
    
        2
  •  0
  •   junaid    7 年前

    我用这个代码做了同样的事情,看一看。

       {let url = URL(string: "https://maps.googleapis.com/maps/api/directions/json?origin=\(self.currentLocation.coordinate.latitude),\(self.currentLocation.coordinate.longitude)&destination=\(33.6165),\(73.0962)&key=yourKey")
        let request = URLRequest(url: url!)
        let config = URLSessionConfiguration.default
        let session = URLSession(configuration: config)
    
        let task = session.dataTask(with: request, completionHandler: {(data, response, error) in
    
            // notice that I can omit the types of data, response and error
            do{
                 let json = JSON(data!)
                let errornum = json["error"]
    
    
                if (errornum == true){
    
                }else{
                    let routes = json["routes"].array
    
                        if routes != nil && (routes?.count)! > 0{
    
                            let overViewPolyLine = routes![0]["overview_polyline"]["points"].string
                            let dict = routes![0].dictionaryValue
                            let distance = dict["legs"]?[0]["distance"]
                            _ = distance?["text"].stringValue
                            let duaration = dict["legs"]?[0]["duration"]
                            _ = duaration?["text"].stringValue
                            //dict["legs"]?["distance"]["text"].stringValue
                            print(overViewPolyLine!)
                if overViewPolyLine != nil{
    
                    DispatchQueue.main.async() {
    
                self.addPolyLineWithEncodedStringInMap(encodedString: overViewPolyLine!)
    
                    }
               }
            }
    }
    

    然后

      {
          func addPolyLineWithEncodedStringInMap(encodedString: String) {
    
    
        let path = GMSPath(fromEncodedPath: encodedString)!
        let polyLine = GMSPolyline(path: path)
        polyLine.strokeWidth = 5
        polyLine.strokeColor = UIColor.yellow
        polyLine.map = self.googleMapsView
        let center = CLLocationCoordinate2D(latitude: 33.6165, longitude: 73.0962)
        let marker = GMSMarker(position: center)
        marker.map = self.googleMapsView
    }
    
    
    func decodePolyline(encodedString: String){
        let polyline = Polyline(encodedPolyline: encodedString)
        let decodedCoordinates: [CLLocationCoordinate2D]? = polyline.coordinates
        for coordinate in decodedCoordinates! {
            let marker = GMSMarker(position: coordinate)
            marker.icon = UIImage(named: "mapPin")
    
             marker.map = self.googleMapsView
        }
    }
    
    推荐文章