package official_climb import ( "math" "github.com/jftuga/geodist" "github.com/martinlehoux/biking_home/ride" ) func MatchClimb(route ride.Ride, climb ride.Climb, officialClimbs []OfficialClimb, policy MatchPolicy) (OfficialClimb, bool) { if policy.Validate() != nil { return OfficialClimb{}, false } bestDistance := math.Inf(1) var best OfficialClimb found := false for _, official := range officialClimbs { startIndex, startDistance := nearestRoutePoint(route, official.StartCoord) endIndex, endDistance := nearestRoutePoint(route, official.EndCoord) if startDistance > policy.EndpointRadiusM || endDistance > policy.EndpointRadiusM { continue } if startIndex >= endIndex { continue } if endIndex < climb.StartIndex() || startIndex > climb.EndIndex() { continue } totalDistance := startDistance + endDistance if totalDistance < bestDistance || (totalDistance == bestDistance && (!found || official.ID < best.ID)) { best = official bestDistance = totalDistance found = true } } return best, found } func nearestRoutePoint(route ride.Ride, target geodist.Coord) (int, float64) { bestIndex := 0 bestDistance := math.Inf(1) for index := 0; index < route.Len(); index++ { distance := distanceM(route.Coord(index), target) if distance < bestDistance { bestIndex = index bestDistance = distance } } return bestIndex, bestDistance } func distanceM(a, b geodist.Coord) float64 { _, distanceKm := geodist.HaversineDistance(a, b) return distanceKm * 1000 }