-
Notifications
You must be signed in to change notification settings - Fork 150
/
Copy pathGPXTrackSegment+MapKit.swift
63 lines (57 loc) · 1.84 KB
/
GPXTrackSegment+MapKit.swift
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
//
// GPXTrackSegment+MapKit.swift
// OpenGpxTracker
//
// Created by merlos on 20/09/14.
//
import Foundation
import UIKit
import MapKit
import CoreGPX
///
/// This extension adds some methods to work with MapKit
///
#if os(iOS)
extension GPXTrackSegment {
/// Returns a MapKit polyline with the points of the segment.
/// This polyline can be directly plotted on the map as an overlay
public var overlay: MKPolyline {
var coords: [CLLocationCoordinate2D] = self.trackPointsToCoordinates()
let pl = MKPolyline(coordinates: &coords, count: coords.count)
return pl
}
}
#endif
extension GPXTrackSegment {
/// Helper method to create the polyline. Returns the array of coordinates of the points
/// that belong to this segment
func trackPointsToCoordinates() -> [CLLocationCoordinate2D] {
var coords: [CLLocationCoordinate2D] = []
for point in self.points {
coords.append(point.coordinate)
}
return coords
}
/// Calculates length in meters of the segment
func length() -> CLLocationDistance {
var length: CLLocationDistance = 0.0
var distanceTwoPoints: CLLocationDistance
// We need at least two points
if self.points.count < 2 {
return length
}
var prev: CLLocation? // Previous
for point in self.points {
let pt: CLLocation = CLLocation(latitude: Double(point.latitude!), longitude: Double(point.longitude!) )
if prev == nil { // If first point => set it as previous and go for next
prev = pt
continue
}
distanceTwoPoints = pt.distance(from: prev!)
length += distanceTwoPoints
// Set current point as previous point
prev = pt
}
return length
}
}