使用按钮更新用户位置并快速绘制路线

时间:2016-09-03 09:22:29

标签: json swift google-maps time location

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

这是逻辑。函数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次,但我不知道为什么会发生这种情况。我怀疑这一定是进程时间的问题,但我不知道如何处理这个问题。

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

谢谢大家。

Pd积:

这些是我的进口商品:

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

这是我的markerLocation变量:

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

    markerLocation = marker.position;
}

1 个答案:

答案 0 :(得分:1)

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

1- locationmanager      func locationManager(manager:CLLocationManager,didUpdateLocations locations:[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()       
        }