【问题标题】:Update user location with a button and draw a route swift使用按钮更新用户位置并快速绘制路线
【发布时间】:2016-09-03 09:22:28
【问题描述】:

我有一个在用户位置和标记之间绘制路线的应用程序。它工作正常,但如果用户更改其位置并按下其他标记,则路线将从第一个位置绘制。

这是逻辑。功能 locationManager 正在停止更新位置以节省电池。这是代码:

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    userLocation = locations[0]
    long = userLocation.coordinate.longitude;
    lat = userLocation.coordinate.latitude;
    locationManager.stopUpdatingLocation()

    if let location = locations.first {

        mapView.camera = GMSCameraPosition(target: location.coordinate, zoom: 14, bearing: 0, viewingAngle: 0)
        }
}

然后我创建一个按钮来更新用户位置并重新绘制折线:

@IBAction func ActualizarLocalizacion(sender: AnyObject) {
    locationManager.startUpdatingLocation()

    originAddresslong = "\(userLocation.coordinate.longitude)"
    originAddresslat = "\(userLocation.coordinate.latitude)"

    if markerLocation == nil
    {markerLocation = userLocation.coordinate
    }

     destinationAddresslong = "\(markerLocation.longitude)"
    destinationAddresslat = "\(markerLocation.latitude)"


    var directionsURLString = baseURLDirections + "origin=" + originAddresslat + "," + originAddresslong + "&destination=" + destinationAddresslat + "," + destinationAddresslong + "&key=MyKey"
    directionsURLString = directionsURLString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
    let directionsURL = NSURL(string: directionsURLString)


    Alamofire.request(.GET, directionsURL!, parameters: nil).responseJSON { response in

        switch response.result {

        case .Success(let data):

            var json = JSON(data)
            print(json)

            let errornum = json["error"]


            if (errornum == true){



            }else{

                //NSThread.sleepForTimeInterval (2)

                var routes = json["routes"].array

                if routes != nil{

                    var overViewPolyLine = routes![0]["overview_polyline"]["points"].string
                    print(overViewPolyLine)
                    if overViewPolyLine != nil{

                        if self.routePolyline != nil {
                            self.routePolyline.map = nil
                            self.routePolyline = nil
                        }


                        let path = GMSMutablePath(fromEncodedPath: overViewPolyLine)
                        self.routePolyline = GMSPolyline(path: path)
                        self.routePolyline.strokeWidth = 5
                        self.routePolyline.strokeColor = UIColor.blueColor()
                        self.routePolyline.map = self.mapView
                        overViewPolyLine = nil
                        routes = nil
                        json = nil

                    }

                }
            }
        case .Failure(let error):

            print("Hubo un problema con el servidor de direcciones: \(error)")
        }

}
}

然后我看到我必须按下按钮 3 次(!!!)才能正确重绘。我已经使用了代码

   locationManager.startUpdatingLocation()

    NSThread.sleepForTimeInterval (2)

然后我只需要推送 2 次,但我不知道为什么会这样。我怀疑这一定是处理时间的问题,但我不知道如何处理。

我在用户点击标记时使用的函数是相同的(公式和变量),在这种情况下只需要一键。

谢谢大家。

警察局:

这些是我的导入:

import UIKit
import GoogleMaps
import SRKUtility
import SRKRequestManager
import Alamofire
import SwiftyJSON

这是我的 markerLocation 变量:

func mapView(mapView: GMSMapView!, didTapMarker marker: GMSMarker!) -> Bool {

    markerLocation = marker.position;
}

【问题讨论】:

    标签: json swift google-maps time location


    【解决方案1】:

    我明白了。最后我分离了按钮和重绘代码,这在locationmanager中已经引入。这是最终代码:

    1- 位置管理器 func locationManager(manager: CLLocationManager, didUpdateLocations 位置: [CLLocation]) {

        userLocation = locations[0]
        long = userLocation.coordinate.longitude;
        lat = userLocation.coordinate.latitude;
    
        originAddresslong = "\(userLocation.coordinate.longitude)"
        originAddresslat = "\(userLocation.coordinate.latitude)"
    
        if markerLocation == nil
        {markerLocation = userLocation.coordinate
        }
    
        destinationAddresslong = "\(markerLocation.longitude)"
        destinationAddresslat = "\(markerLocation.latitude)"
    
    
    
        var directionsURLString = baseURLDirections + "origin=" + originAddresslat + "," + originAddresslong + "&destination=" + destinationAddresslat + "," + destinationAddresslong + "&key=AIzaSyB4xO_8B0ZoA8lsAgRjqpqJjgWHbb5X3u0"
        directionsURLString = directionsURLString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
        let directionsURL = NSURL(string: directionsURLString)
    
    
        Alamofire.request(.GET, directionsURL!, parameters: nil).responseJSON { response in
    
            switch response.result {
    
            case .Success(let data):
    
                var json = JSON(data)
                print(json)
    
                let errornum = json["error"]
    
    
                if (errornum == true){
    
    
    
                }else{
    
                    //NSThread.sleepForTimeInterval (2)
    
                    var routes = json["routes"].array
    
                    if routes != nil{
    
                        var overViewPolyLine = routes![0]["overview_polyline"]["points"].string
                        let distancia = routes![0]["legs"][0]["distance"]["text"].string
                        if overViewPolyLine != nil{
    
                            if self.routePolyline != nil {
                                self.routePolyline.map = nil
                                self.routePolyline = nil
                            }
    
    
                            let path = GMSMutablePath(fromEncodedPath: overViewPolyLine)
                            self.routePolyline = GMSPolyline(path: path)
                            self.routePolyline.strokeWidth = 5
                            self.routePolyline.strokeColor = UIColor.blueColor()
                            self.routePolyline.map = self.mapView
    
                            self.DistanciaLabel.setTitle(distancia,forState: UIControlState.Normal)
    
                            overViewPolyLine = nil
                            routes = nil
                            json = nil
    
                        }
    
                    }
                }
            case .Failure(let error):
    
                print("Hubo un problema con el servidor de direcciones: \(error)")
            }
    
        }
    
        locationManager.stopUpdatingLocation()
    
        if let location = locations.first {
            mapView.camera = GMSCameraPosition(target: location.coordinate, zoom: 14, bearing: 0, viewingAngle: 0)
    
        }
    
    }
    

    2- 按钮

        @IBAction func ActualizarLocalizacion(sender: AnyObject) {
        locationManager.startUpdatingLocation()       
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-24
      • 2020-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多