Skip to content

Instantly share code, notes, and snippets.

@andr3a88
Last active April 13, 2018 10:57
Show Gist options
  • Save andr3a88/1f84d053d8888cdf62859f5a031d6519 to your computer and use it in GitHub Desktop.
Save andr3a88/1f84d053d8888cdf62859f5a031d6519 to your computer and use it in GitHub Desktop.
Switch route on tap like Google Maps
class RoutesViewController {
/// ...
func mapView(_ mapView: GMSMapView, didTapAt coordinate: CLLocationCoordinate2D) {
if let index = self.shouldSelectPath(mapView, coordinate: coordinate, routes: results, currentRouteIndex: routeIndex) {
routeIndex = index
updateRoute()
}
}
private func shouldSelectPath(_ mapView: GMSMapView, coordinate: CLLocationCoordinate2D, routes: [PXGoogleDirectionsRoute], currentRouteIndex: Int) -> Int? {
for (index, route) in routes.enumerated() where index != currentRouteIndex {
if self.getMinDistance(mapView, path: route.path!, coordinate: coordinate) < 20 {
return index
}
}
return nil
}
private func getMinDistance(_ mapView: GMSMapView, path: GMSPath, coordinate: CLLocationCoordinate2D) -> Double {
var minDistance: Double = Double.infinity
for pathPointIndex in 0..<path.count() {
let pathCoordinate = path.coordinate(at: pathPointIndex)
let distance = mapView.distanceInPoints(coordinate1: coordinate, coordinate2: pathCoordinate)
if distance < minDistance {
minDistance = distance
}
}
return minDistance
}
}
// MARK: GMSMapView
extension GMSMapView {
/// Returns the distance in point between CLLocationCoordinate2D
///
/// - Parameters:
/// - coordinate1: The first coordinate
/// - coordinate2: The second coordinate
/// - Returns: The distance
func distanceInPoints(coordinate1: CLLocationCoordinate2D, coordinate2: CLLocationCoordinate2D) -> Double {
let selectedPoint = self.projection.point(for: coordinate1)
let pathPoint = self.projection.point(for: coordinate2)
return Double(selectedPoint.distance(toPoint: pathPoint))
}
}
// MARK: CGPoint
extension CGPoint {
/// Get the distance from a point
///
/// - Parameter p: The point
/// - Returns: The distance
func distance(toPoint p:CGPoint) -> CGFloat {
return sqrt(pow(x - p.x, 2) + pow(y - p.y, 2))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment