使用Timer在Swift 3

时间:2016-11-07 17:56:07

标签: swift google-maps maps swift3

免责声明:非常初级的编码员,所以请原谅任何“明显”的错误。

我正在尝试构建一个应用程序,向用户显示它们与标记的距离。

我有一个GoogleMaps地图视图,我想连续刷新用户位置(每次说3秒)。从标记计算并打印其线性距离(以米为单位),并将其设置为我的左侧导航项按钮。

我尝试通过GoogleMaps这样做无济于事。所以尝试使用CLLocation和CoreLocation。

问题是,我以米(15米)获得第一个值,3秒后获得第二个值(9米),然后我的计时器的每隔3秒迭代只能永久地给出9米,无论我是否移动(以及我的googlemaps视图)当我移动,笔记本电脑和链接的ipad在手中时,会成功更新蓝色用户位置点。

我正在做的是让我的计时器每3秒触发一次“findDistance”功能。 “findDistance”函数运行locationmanager(将globalUserLocation设置为当前值 - 如果我没有做错的话),计算距离并将其设置为GlobalDistance,然后将左侧导航按钮项更新为新的距离。

但似乎用户位置只更新两次(而不是每3秒更新一次)。

我做错了什么?任何帮助将不胜感激

我添加了所有plist要求,这是我的代码:

import UIKit
import GoogleMaps
import CoreLocation
import MapKit

class googleMaps: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
    let locationmanager = CLLocationManager()
    var globalDistance: CLLocationDistance = 0
    var mapView: GMSMapView? = nil
    var globalUserLocation = CLLocation(latitude: 40.085260, longitude: 22.601468)

    override func viewDidLoad() {
        super.viewDidLoad()

        let timer = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(googleMaps.findDistance), userInfo: nil, repeats: true)
        self.locationmanager.delegate = self
        self.locationmanager.desiredAccuracy = kCLLocationAccuracyBest
        self.locationmanager.startUpdatingLocation()

        timer.fire()

        GMSServices.provideAPIKey("**mykeyhere**")

        let camera = GMSCameraPosition.camera(withLatitude: 40.085260 , longitude: 22.601468, zoom: 40)

        mapView = GMSMapView.map(withFrame: CGRect(origin: CGPoint(x: 0,y :0), size: CGSize(width: 200, height: 500)), camera: camera)
        mapView?.isMyLocationEnabled = true

        view = mapView

        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "\(globalDistance)", style: UIBarButtonItemStyle.plain, target: self, action: #selector(googleMaps.next as (googleMaps) -> () -> ()))

        mapView?.mapType = kGMSTypeNormal
        self.mapView?.settings.myLocationButton = true
        self.mapView?.settings.compassButton = true
    }

    func locationmanager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        globalUserLocation = locations.last!
    }

    func findDistance(){
        locationmanager
        let currentLat = locationmanager.location!.coordinate.latitude
        let currentLong = locationmanager.location!.coordinate.longitude

        globalUserLocation = CLLocation(latitude: currentLat, longitude: currentLong)

        let myMarker = CLLocation(latitude: 40.085260, longitude: 22.601468)

        if globalUserLocation != nil {
            let distance = globalUserLocation.distance(from: myMarker)
            print(distance)

            globalDistance = distance
            navigationItem.leftBarButtonItem?.title = "\(globalDistance)"
        }
    }

0 个答案:

没有答案