Blame view

HDFwear/Motion/StartMotionVC.swift 25 KB
f2cf74c7   yangbin   1.0.20(4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
  //
  //  StartMotionVC.swift
  //  Twear
  //
  //  Created by yangbin on 2021/12/28.
  //
  
  import UIKit
  import SnapKit
  import SwiftDate
  import CoreLocation
  import MBProgressHUD
  import HCKalmanFilter
  
  class StartMotionVC: UIViewController {
      
      @IBOutlet weak var mapBackView: UIView!
      @IBOutlet weak var countImageView: UIImageView!
      @IBOutlet weak var detailView: UIView!
      
      @IBOutlet weak var typeImageView: UIImageView!
      @IBOutlet weak var stopButton: ProgressButton!
      @IBOutlet weak var mapButton: UIButton!
      
      @IBOutlet weak var startButton: UIButton!
      @IBOutlet weak var pauseButton: UIButton!
      @IBOutlet weak var calorieLabel: UILabel!
      @IBOutlet weak var timeLabel: UILabel!
      
      
      @IBOutlet weak var signalImageView: UIImageView!
      @IBOutlet weak var gpsLabel: UILabel!
      @IBOutlet weak var signalImageView1: UIImageView!
      @IBOutlet weak var gpsView: UIView!
      @IBOutlet weak var motionTypeLabel: UILabel!
      
      @IBOutlet weak var mapTimeLabel: UILabel!
      
      
      @IBOutlet weak var mapDistanceLabel: UILabel!
      @IBOutlet weak var distanceLabel: UILabel!
      @IBOutlet weak var speedLabel: UILabel!
      
      @IBOutlet weak var speedUnitLabel: UILabel!
      @IBOutlet weak var unitLabel: UILabel!
      @IBOutlet weak var unitLabel1: UILabel!
      
      private lazy var traceManager: MATraceManager! = MATraceManager()
      
      let user = UserInfo
      
      private lazy var mapView: MAMapView = MAMapView()
      private var count: Int = 3
      
      private var speedArray: [Float] = []
      var isRecord: Bool = false
      var motionType: TrainType = .running
      var time: Int = 0
      var distance: Float = 0
      var speed: Float = 0
      var calorie: Float = 0
      var startDate = Date()
      
      var coordinateArray: [CLLocationCoordinate2D] = []
      var locationArray: [CLLocation] = []
      var stepCadenceArray: [Int] = []
      var altitudeArray: [Double] = []
      
      
      var resetKalmanFilter: Bool = false
      var hcKalmanFilter: HCKalmanAlgorithm?
      
      private lazy var locationManager: AMapLocationManager = AMapLocationManager()
      
      override func viewDidAppear(_ animated: Bool) {
          super.viewDidAppear(animated)
          
          GCDTimer.shared.scheduledDispatchTimer(WithTimerName: "count_down", timeInterval: 1, queue: .main, repeats: true) {[weak self] in
              self?.countDown()
          }
          locationManager.startUpdatingLocation()
          locationManager.startUpdatingHeading()
      }
      
      override func viewDidLoad() {
          super.viewDidLoad()
          stopButton.progressClosure = { [weak self] in
              self?.stopMotion()
              //            self?.dismiss(animated: true)
          }
          
          var motionTypeText = "户外跑步"
          var typeImageName = "motion_run"
          switch motionType {
          case .run_indoor:
              motionTypeText = "室内跑步"
          case .walking:
              motionTypeText = "步行"
              typeImageName = "motion_walking"
          case .bicycle:
              motionTypeText = "骑行"
              typeImageName = "motion_bicycle"
          case .mountaineering:
              motionTypeText = "爬山"
              typeImageName = "motion_mountaineering"
          default:
              break
          }
          typeImageView.image = UIImage(named: typeImageName)
          motionTypeLabel.text = LocString(motionTypeText)
          
          if user.distanceUnit == 0 {
              speedUnitLabel.text = LocString("公里/分钟")
              unitLabel.text = LocString("公里")
              unitLabel1.text = LocString("公里")
          } else {
              speedUnitLabel.text = LocString("英里/分钟")
              unitLabel.text = LocString("英里")
              unitLabel1.text = LocString("英里")
          }
          
          initMapView()
      }
      
      func initMapView() {
          MAMapView.updatePrivacyShow(.didShow, privacyInfo: .didContain)
          MAMapView.updatePrivacyAgree(.didAgree)
          AMapServices.shared().enableHTTPS = true
          mapView.showsUserLocation = false
          let compassX = mapView.compassOrigin.x
          mapView.compassOrigin = CGPoint(x: compassX-5, y: 120)
          mapView.userTrackingMode = .followWithHeading
          mapView.zoomLevel = 17.5
          mapView.delegate = self
          mapView.mapLanguage = (AppSettings.shared.language == .Chinese) ? 0 : 1
          //        mapView.distanceFilter = 10
          //        mapView.desiredAccuracy = kCLLocationAccuracyBestForNavigation
          mapView.frame = mapBackView.frame
          
          mapBackView.addSubview(mapView)
          mapBackView.sendSubviewToBack(mapView)
          
          mapBackView.isHidden = true
          
          locationManager.delegate = self
          
          locationManager.pausesLocationUpdatesAutomatically = false
          //        locationManager.allowsBackgroundLocationUpdates = true
          if motionType == .run_indoor {
              locationManager.distanceFilter = 12
              
          } else {
              locationManager.distanceFilter = 23
          }
          
         
  
          locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
          locationManager.allowsBackgroundLocationUpdates = true
          //        locationManager.startUpdatingLocation()
      }
      
      func startMotion() {
          time += 1
          timeLabel.toTimeType3(length: time)
          mapTimeLabel.toTimeType3(length: time)
      }
      
      func stopMotion() {
          isRecord = false
          if distance >= 500 {
              var altitude: Double = 0
              if let minAltitude = locationArray.min(\.altitude)?.altitude, let maxAltitude = locationArray.max(\.altitude)?.altitude {
                  altitude = maxAltitude - minAltitude
              }
              var coordinateStr = ""
              for coordinate in coordinateArray {
                  coordinateStr += "\(coordinate.latitude),\(coordinate.longitude)|"
              }
              coordinateStr = coordinateStr.substring(toIndex: coordinateStr.count-1)
              var speedStr = ""
              for speed in speedArray {
                  speedStr += "\(speed)|"
              }
              speedStr = speedStr.substring(toIndex: speedStr.count-1)
              var stepCadenceStr = ""
              for cadence in stepCadenceArray {
                  stepCadenceStr += "\(cadence)|"
              }
              stepCadenceStr = stepCadenceStr.substring(toIndex: stepCadenceStr.count-1)
              var altitudeStr = ""
              for alt in altitudeArray {
                  altitudeStr += "\(alt)|"
              }
              altitudeStr = altitudeStr.substring(toIndex: altitudeStr.count-1)
              
              let motion = MotionModel(type: motionType, date: DateInRegion().date - time.seconds, length: time, calorie: calorie, distance: Int(distance), steps: distanceToStep(distance), altitude: altitude, coordinateArray: coordinateStr, speedArray: speedStr, stepCadenceArray: stepCadenceStr, altitudeArray: altitudeStr)
              motion.add()
              MedalModel.update(motion: motion)
              //            MBProgressHUD.showh("..test")
              let vc = UIStoryboard.loadViewControllerIdentifier(storyboardName: "Motion", identifier: "EndMotionVC") as! EndMotionVC
              vc.modalPresentationStyle = .fullScreen
              vc.coordinateArray = coordinateArray
              vc.calorie = calorie
              vc.distance = distance
              vc.length = time
              vc.date = startDate
              vc.speedArray = speedArray
              vc.motionType = motionType
              vc.altitudeArray = altitudeArray
              vc.stepCadenceArray = stepCadenceArray
              vc.altitude = altitude
              self.present(vc, animated: true, completion: nil)
              //            self.dismiss(animated: true, completion: nil)
          } else {
              let view = BottomAlertView(title: LocString("本次运动距离太短,将不保存记录"), sureText: LocString("我知道了"))
              view.clickClosure = {[weak self] index in
                  self?.dismiss(animated: true)
              }
              view.show()
          }
      }
      
      @IBAction func continueMotion(_ sender: Any) {
          isRecord = true
          showStopButton(false)
          GCDTimer.shared.scheduledDispatchTimerNotNow(WithTimerName: "StartMotion", timeInterval: 1, queue: .main, repeats: true) { [weak self] in
              self?.startMotion()
          }
      }
      
      @IBAction func pauseMotion(_ sender: Any) {
          isRecord = false
          showStopButton(true)
          if GCDTimer.shared.isExistTimer(WithTimerName: "StartMotion") {
              GCDTimer.shared.cancleTimer(WithTimerName: "StartMotion")
          }
      }
      
      
      func showStopButton(_ isShow: Bool) {
          pauseButton.isHidden = isShow
          self.startButton.isHidden = !isShow
          self.stopButton.isHidden = !isShow
          let centerX = isShow ? SCREEN_WIDTH/2*0.55 : SCREEN_WIDTH/2
          UIView.animate(withDuration: 0.3) {
              self.stopButton.center.x = centerX
              self.startButton.center.x = SCREEN_WIDTH-centerX
          } completion: { finish in
          }
      }
      
      func countDown() {
          if count >= 0 {
              countImageView.image = UIImage(named: "count_down_\(count)")
              let animation = CABasicAnimation(keyPath: "transform.scale")
              animation.fromValue = 0.5
              animation.toValue = 1
              animation.duration = 0.5
              animation.beginTime = 0
              if count == 1 {
                  hideMap(1)
              }
              self.countImageView.layer.add(animation, forKey: nil)
              count -= 1
          } else {
              if GCDTimer.shared.isExistTimer(WithTimerName: "count_down") {
                  GCDTimer.shared.cancleTimer(WithTimerName: "count_down")
              }
              self.countImageView.isHidden = true
              if motionType == .run_indoor {
                  self.mapButton.isHidden = true
                  self.signalImageView.isHidden = true
                  self.gpsLabel.isHidden = true
              } else {
                  self.mapButton.isHidden = false
                  self.signalImageView.isHidden = false
                  self.gpsLabel.isHidden = false
              }
              self.detailView.isHidden = false
              
              self.motionTypeLabel.isHidden = false
              
              isRecord = true
              startDate = DateInRegion().date
              GCDTimer.shared.scheduledDispatchTimerNotNow(WithTimerName: "StartMotion", timeInterval: 1, queue: .main, repeats: true) { [weak self] in
                  self?.startMotion()
              }
              locationManager.startUpdatingLocation()
  //            resetKalmanFilter = true
          }
      }
      
      
      @IBAction func showMap(_ sender: Any) {
          mapBackView.isHidden = false
          mapBackView.isUserInteractionEnabled = false
          UIView.animate(withDuration: 0.3) {
              self.mapBackView.center = self.view.center
              self.mapBackView.transform = .identity
              //            self.view.layoutIfNeeded()
          } completion: { finish in
              self.mapBackView.isUserInteractionEnabled = true
          }
          
      }
      
      @IBAction func hideMap(_ sender: Any) {
          UIView.animate(withDuration: 0.3) {
              self.mapBackView.transform = CGAffineTransform.init(scaleX: 0.02, y: 0.02)
              self.mapBackView.center = self.mapButton.center
              //            self.view.layoutIfNeeded()
          } completion: { finish in
              self.mapBackView.isHidden = true
          }
      }
      
      deinit {
          print("deinit\(NSStringFromClass(type(of: self)))!!!!!!!")
      }
      
      private func distanceToCalorie(_ distance: Float) -> Float {
          let user = UserInfo
          var weight = user.weight
          if user.weight < 15 {
              weight = 65
          }
          if user.gender == 1 {
              return Float((weight - 10)) * distance
          } else {
              return Float((weight - 10)) * distance * 1.3
          }
      }
      
      func updateSignal(_ accuracy: CLLocationAccuracy) {
          var signal: Int = 3
          if accuracy < 0 {
              signal = 0
          } else if accuracy > 143 {
              signal = 1
          } else if accuracy > 48 {
              signal = 2
          } else {
              signal = 3
          }
          signalImageView.image = UIImage(named: "signal_\(signal)")
          signalImageView1.image = UIImage(named: "signal_map_\(signal)")
      }
      
      
      private func distanceToStepCadence(_ distance: Float, time: Int) -> Int {
          let user = UserInfo
          if user.gender == 1 {
              return Int (distance * 100 / 0.4 / Float(user.height)) * 60 / time
          } else {
              return Int (distance * 100 / 0.35 / Float(user.height)) * 60 / time
          }
      }
      
      private func distanceToStep(_ distance: Float) -> Int {
          let user = UserInfo
          if user.gender == 1 {
              return Int (distance * 100 / 0.4 / Float(user.height))
          } else {
              return Int (distance * 100 / 0.35 / Float(user.height))
          }
      }
      
  }
  
  extension StartMotionVC: AMapLocationManagerDelegate {
      
      
      func amapLocationManager(_ manager: AMapLocationManager!, didUpdate location: CLLocation!) {
          //        mapView.showsUserLocation
          
      
          
          if !isRecord {
              return
          }
          //        if !updatingLocation {
          //            return
          
          //        }
          //        guard let location = userLocation.location else {
          //            return
          //        }
          print("信号强度:\(location.horizontalAccuracy)")
          updateSignal(location.horizontalAccuracy)
          if coordinateArray.count == 0 {
              //            coordinateArray.append(location.coordinate)
              //            locationArray.append(location)
          } else {
             
              
              let lastCoordinate = coordinateArray.last!
              let point1 = MAMapPointForCoordinate(lastCoordinate)
              let point2 = MAMapPointForCoordinate(location.coordinate)
              let dis = MAMetersBetweenMapPoints(point1, point2)
              //            print(Float(dis))
              distance += Float(dis)
              //            print(distance)
              if distance == 0 {
                  return
              }
              
              if user.distanceUnit == 0 {
                  distanceLabel.text = String(format:"%.2f", distance/1000)
                  mapDistanceLabel.text = String(format:"%.2f", distance/1000)
                  speed = Float(time)/(distance/1000)
                  if speed > 0 {
                      speedArray.append(speed)
                  }
                  speedLabel.text = "\(String(format:"%02d", Int(speed)/60))\(String(format:"%02d", Int(speed)%60))″"
              } else {
                  distanceLabel.text = (distance/1000).footString()
                  mapDistanceLabel.text = (distance/1000).footString()
                  speed = Float(time)/(distance/1000)
                  if speed > 0 {
                      speedArray.append(speed)
                  }
                  speedLabel.text = "\(String(format:"%02d", Int(speed/0.6213)/60))\(String(format:"%02d", Int(speed/0.6213)%60))″"
              }
              
              
              calorie = distanceToCalorie(distance/1000)
              calorieLabel.text = String(format:"%.2f", calorie)
              if time > 0 {
                  stepCadenceArray.append(distanceToStepCadence(distance, time: time))
              }
              altitudeArray.append(Double(location.altitude))
          }
          
          print("添加")
          if hcKalmanFilter == nil {
              self.hcKalmanFilter = HCKalmanAlgorithm(initialLocation: location)
              hcKalmanFilter?.rValue = 40
              hcKalmanFilter?.resetKalman(newStartLocation: location)
              self.coordinateArray.append(location.coordinate)
              self.locationArray.append(location)
          } else {
              let kalmanLocation = hcKalmanFilter?.processState(currentLocation: location)
  //            print("\(kalmanLocation?.coordinate) ---  \(location.coordinate)")
              self.coordinateArray.append(kalmanLocation!.coordinate)
              self.locationArray.append(kalmanLocation!)
          }
          updatePath()
  //        let kalmanLocation = hcKalmanFilter?.processState(currentLocation: location)
  //        print(kalmanLocation!.coordinate)
          //        print(location!.getDistanceFrom(userLocation.location))
         
      }
  }
  
  
  extension StartMotionVC: MAMapViewDelegate {
      //    func mapView(_ mapView: MAMapView!, viewFor annotation: MAAnnotation!) -> MAAnnotationView! {
      //          if annotation is MAUserLocation {
      //              var userView = mapView.dequeueReusableAnnotationView(withIdentifier: "userAnnotationIdentifer")
      //              if userView == nil {
      //                  userView = MAAnnotationView(annotation: annotation, reuseIdentifier: "userAnnotationIdentifer")
      //              }
      //              userView!.image = UIImage(named: "firmware_update")
      //              return userView!
      //          }
      //          return nil
      //      }
      
      
      
      func mapView(_ mapView: MAMapView!, didUpdate userLocation: MAUserLocation!, updatingLocation: Bool) {
          //        if updatingLocation {
          //            let userView = mapView.view(for: userLocation)
          //
          //                   //取方向信息
          //            if let userHeading = userLocation.heading {
          //                //根据方向旋转箭头
          //                userView?.rotateWithHeading(heading: userHeading)
          //            }
          
          
          //        }
          /*
           if !isRecord {
           return
           }
           if !updatingLocation {
           return
           }
           guard let location = userLocation.location else {
           return
           }
           if coordinateArray.count == 0 {
           coordinateArray.append(location.coordinate)
           } else {
           let lastCoordinate = coordinateArray.last!
           let point1 = MAMapPointForCoordinate(lastCoordinate)
           let point2 = MAMapPointForCoordinate(location.coordinate)
           let dis = MAMetersBetweenMapPoints(point1, point2)
           //            print(Float(dis))
           distance += Float(dis)
           //            print(distance)
           if distance == 0 {
           return
           }
           distanceLabel.text = String(format:"%.2f", distance/1000)
           mapDistanceLabel.text = String(format:"%.2f", distance/1000)
           speed = Float(time)/(distance/1000)
           speedLabel.text = "\(String(format:"%02d", Int(speed)/60))\(String(format:"%02d", Int(speed)%60))″"
           calorieLabel.text = String(format:"%.2f", distanceToCalorie(distance/1000)/1000)
           }
           
           print("添加")
           //        print(location!.getDistanceFrom(userLocation.location))
           self.coordinateArray.append(location.coordinate)
           
           updatePath()
           */
          //        if isRecording {
          //            // filter the result
          //            if userLocation.location.horizontalAccuracy < 100.0 {
          //
          //                addLocation(location: userLocation.location)
          //            }
          //        }
          //
          //        var speed = location!.speed
          //        if speed < 0.0 {
          //            speed = 0.0
          //        }
          //
          //        let infoArray: [(String, String)] = [
          //            ("coordinate", NSString(format: "<%.4f, %.4f>", location!.coordinate.latitude, location!.coordinate.longitude) as String),
          //            ("speed", NSString(format: "%.2fm/s(%.2fkm/h)", speed, speed * 3.6) as String),
          //            ("accuracy", "\(location!.horizontalAccuracy)m"),
          //            ("altitude", NSString(format: "%.2fm", location!.altitude) as String)]
          //
          //        statusView!.showStatusInfo(info: infoArray)
          
      }
      
      func updatePath () {
          
          // 每次获取到新的定位点重新绘制路径
          /*
           var mArr = [MATraceLocation]()
           for loc: CLLocation in self.locationArray {
           let tLoc = MATraceLocation()
           tLoc.loc = loc.coordinate
           tLoc.speed = loc.speed * 3.6
           //m/s   km/h
           tLoc.time = loc.timestamp.timeIntervalSince1970 * 1000
           tLoc.angle = loc.course
           mArr.append(tLoc)
           }
           weak var weakSelf = self
           
           _ = traceManager.queryProcessedTrace(with: mArr, type: .aMap, processingCallback: { (index:Int32, arr:[MATracePoint]?) in
           
           }, finishCallback: { (arr:[MATracePoint]?, distance:Double) in
           //            if saving {
           //                weakSelf?.totalTraceLength = 0.0
           //                weakSelf?.currentRecord?.updateTracedLocations(arr)
           //                weakSelf?.saveRoute()
           //                weakSelf?.isSaving = false
           //                weakSelf?.showTip(tip: "recording save done")
           //            }
           //            weakSelf?.updateUserlocationTitle(withDistance: distance)
           weakSelf?.addFullTrace(arr)
           
           }, failedCallback: { (errCode:Int32, errDesc:String?) in
           print(errDesc ?? "error")
           //            weakSelf?.isSaving = false
           })
           */
          // 移除掉除之前的overlay
          let overlays = self.mapView.overlays
          self.mapView.removeOverlays(overlays)
          
          let polyline = MAPolyline(coordinates: &self.coordinateArray, count: UInt(self.coordinateArray.count))
          self.mapView.add(polyline)
          
          // 将最新的点定位到界面正中间显示
          let lastCoord = self.coordinateArray[self.coordinateArray.count - 1]
          self.mapView.setCenter(lastCoord, animated: true)
      }
      
      
      func addFullTrace(_ tracePoints: [MATracePoint]?) {
          let polyline: MAPolyline? = self.makePolyline(with: tracePoints)
          if polyline == nil {
              return
          }
          //          self.tracedPolylines.append(polyline!)
          self.mapView.add(polyline!)
          if let lastCoord = self.coordinateArray.last {
              self.mapView.setCenter(lastCoord, animated: true)
          }
      }
      
      func makePolyline(with tracePoints: [MATracePoint]?) -> MAPolyline? {
          if tracePoints == nil || tracePoints!.count < 2 {
              return nil
          }
          var pCoords = [CLLocationCoordinate2D]()
          
          for i in 0..<tracePoints!.count {
              pCoords.append(CLLocationCoordinate2D(latitude: tracePoints![i].latitude, longitude: tracePoints![i].longitude))
          }
          
          let polyline = MAPolyline(coordinates: &pCoords, count: UInt(pCoords.count))
          
          return polyline
      }
      
      func mapView(_ mapView: MAMapView!, rendererFor overlay: MAOverlay!) -> MAOverlayRenderer! {
          if let poly = overlay as? MAPolyline {
              let polylineView = MAPolylineRenderer(polyline: poly)
              polylineView!.lineWidth = 6
              polylineView!.strokeColor = UIColor(red: 4 / 255.0, green:  181 / 255.0, blue:  108 / 255.0, alpha: 1.0)
              polylineView!.lineJoinType = kMALineJoinRound
              polylineView!.lineCapType = kMALineCapRound
              return polylineView
          } else {
              return nil
          }
      }
      //
      //    func mapView(mapView: MAMapView!, viewForOverlay overlay: MAOverlay!) -> MAOverlayView! {
      //        if overlay.isKindOfClass(MAPolyline) {
      //            let polylineView = MAPolylineView(overlay: overlay)
      //            polylineView.lineWidth = 6
      //            polylineView.strokeColor = UIColor(red: 4 / 255.0, green:  181 / 255.0, blue:  108 / 255.0, alpha: 1.0)
      //
      //            return polylineView
      //        }
      //
      //        return nil
      //    }
      
      func mapView(_ mapView: MAMapView, didChange mode: MAUserTrackingMode, animated: Bool) {
          //        if mode == MAUserTrackingMode.none {
          //            locationButton?.setImage(imageNotLocate, for: UIControlState.normal)
          //        }
          //        else {
          //            locationButton?.setImage(imageLocated, for: UIControlState.normal)
          //        }
      }
      
  }
  extension MAAnnotationView {
      
      /// 根据heading信息旋转大头针视图
      ///
      /// - Parameter heading: 方向信息
      func rotateWithHeading(heading: CLHeading) {
          
          //将设备的方向角度换算成弧度
          let headings = Double.pi * heading.magneticHeading / 180.0
          //创建不断旋转CALayer的transform属性的动画
          let rotateAnimation = CABasicAnimation(keyPath: "transform")
          //动画起始值
          let formValue = self.layer.transform
          rotateAnimation.fromValue = NSValue(caTransform3D: formValue)
          //绕Z轴旋转heading弧度的变换矩阵
          let toValue = CATransform3DMakeRotation(CGFloat(headings), 0, 0, 1)
          //设置动画结束值
          rotateAnimation.toValue = NSValue(caTransform3D: toValue)
          rotateAnimation.duration = 0.35
          rotateAnimation.isRemovedOnCompletion = true
          //设置动画结束后layer的变换矩阵
          self.layer.transform = toValue
          
          //添加动画
          self.layer.add(rotateAnimation, forKey: nil)
          
      }
  }