Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add tripplanner and map overlay #35

Merged
merged 5 commits into from
Jul 31, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions OTPKit/Features/MapExtension/MapMarkingView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ public struct MapMarkingView: View {
Button {
locationManagerService.toggleMapMarkingMode(false)
locationManagerService.selectAndRefreshCoordinate()
locationManagerService.removeOriginDestinationData()
} label: {
Text("Cancel")
.padding(8)
Expand All @@ -33,6 +34,7 @@ public struct MapMarkingView: View {

Button {
locationManagerService.toggleMapMarkingMode(false)
locationManagerService.addOriginDestinationData()
locationManagerService.selectAndRefreshCoordinate()
} label: {
Text("Add Pin")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ public struct OriginDestinationSheetView: View {
ForEach(locationManagerService.completions) { location in
Button(action: {
locationManagerService.appendMarker(location: location)

locationManagerService.addOriginDestinationData()
switch UserDefaultsServices.shared.saveRecentLocations(data: location) {
case .success:
dismiss()
Expand All @@ -192,6 +192,7 @@ public struct OriginDestinationSheetView: View {
if let userLocation = locationManagerService.currentLocation {
Button(action: {
locationManagerService.appendMarker(location: userLocation)
locationManagerService.addOriginDestinationData()
switch UserDefaultsServices.shared.saveRecentLocations(data: userLocation) {
case .success:
dismiss()
Expand Down
76 changes: 76 additions & 0 deletions OTPKit/Features/TripPlanner/TripPlannerSheetView.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
//
// TripPlannerSheetView.swift
// OTPKit
//
// Created by Hilmy Veradin on 25/07/24.
//

import SwiftUI

public struct TripPlannerSheetView: View {
@ObservedObject private var locationManagerService = LocationManagerService.shared
@Environment(\.dismiss) var dismiss

public init() {}

private func formatTimeDuration(_ duration: Int) -> String {
if duration < 60 {
return "Total duration: \(duration) second\(duration > 1 ? "s" : "")"
} else if duration < 3600 {
let minutes = Double(duration) / 60
return String(format: "Total duration: %.1f minutes", minutes)
} else {
let hours = Double(duration) / 3600
return String(format: "Total duration: %.1f hours", hours)
}
}

private func formatDistance(_ distance: Int) -> String {
if distance < 1000 {
return "Total distance: \(distance) meters"
} else {
let miles = Double(distance) / 1609.34
return String(format: "Total distance: %.1f miles", miles)
}
}

public var body: some View {
VStack {
if let itineraries = locationManagerService.planResponse?.plan?.itineraries {
List(itineraries, id: \.self) { itinerary in
let distance = itinerary.legs.map(\.distance).reduce(0, +)
Button(action: {
locationManagerService.selectedItinerary = itinerary
locationManagerService.planResponse = nil
dismiss()
}, label: {
VStack(alignment: .leading) {
Text(formatTimeDuration(itinerary.duration))
Text(formatDistance(Int(distance)))
}

})
}
} else {
Text("Can't find trip planner. Please try another pin point")
}

Button(action: {
locationManagerService.resetTripPlanner()
dismiss()
}, label: {
Text("Cancel")
.frame(maxWidth: .infinity)
.padding()
.background(Color.gray)
.foregroundStyle(Color.white)
.clipShape(RoundedRectangle(cornerRadius: 12))
.padding(.horizontal, 16)
})
}
}
}

#Preview {
TripPlannerSheetView()
}
46 changes: 46 additions & 0 deletions OTPKit/Features/TripPlanner/TripPlannerView.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
//
// TripPlannerView.swift
// OTPKit
//
// Created by Hilmy Veradin on 30/07/24.
//

import SwiftUI

public struct TripPlannerView: View {
@ObservedObject private var locationManagerService = LocationManagerService.shared

public init() {}

public var body: some View {
VStack {
Button(action: {
locationManagerService.resetTripPlanner()
}, label: {
Text("Start")
})
.frame(maxWidth: .infinity)
.padding()
.background(Color.gray)
.foregroundStyle(Color.white)
.clipShape(RoundedRectangle(cornerRadius: 12))
.padding(.horizontal, 16)

Button(action: {
locationManagerService.resetTripPlanner()
}, label: {
Text("Cancel")
})
.frame(maxWidth: .infinity)
.padding()
.background(Color.gray)
.foregroundStyle(Color.white)
.clipShape(RoundedRectangle(cornerRadius: 12))
.padding(.horizontal, 16)
}
}
}

#Preview {
TripPlannerView()
}
6 changes: 6 additions & 0 deletions OTPKit/Models/TripPlanner/Step.swift
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,10 @@ public struct Step: Codable, Hashable {

/// Optional elevation change during this step, in meters.
public let elevationChange: Double?

/// Longitude of the place.
public let lon: Double

/// Latitude of the place.
public let lat: Double
}
147 changes: 138 additions & 9 deletions OTPKit/Services/LocationManagerService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,21 @@ public final class LocationManagerService: NSObject, ObservableObject {

// MARK: - Properties

// API Client
private let apiClient = RestAPI(
baseURL: URL(string: "https://otp.prod.sound.obaweb.org/otp/routers/default/")!
)

// Trip Planner
@Published public var planResponse: OTPResponse?
@Published public var isFetchingResponse = false
@Published public var tripPlannerErrorMessage: String?
@Published public var selectedItinerary: Itinerary?

// Origin Destination
@Published public var originDestinationState: OriginDestinationState = .origin
@Published public var originCoordinate = CLLocationCoordinate2D(latitude: 0, longitude: 0)
@Published public var destinationCoordinate = CLLocationCoordinate2D(latitude: 0, longitude: 0)
@Published public var originCoordinate: CLLocationCoordinate2D?
@Published public var destinationCoordinate: CLLocationCoordinate2D?

// Location Search
private let completer: MKLocalSearchCompleter
Expand Down Expand Up @@ -102,19 +113,35 @@ public final class LocationManagerService: NSObject, ObservableObject {
case .origin:
selectedMapPoint["origin"] = markerItem
changeMapCamera(mapItem)
originName = mapItem.name ?? "Location unknown"
originCoordinate = coordinate
case .destination:
selectedMapPoint["destination"] = markerItem
changeMapCamera(mapItem)
destinationName = mapItem.name ?? "Location unknown"
destinationCoordinate = coordinate
}
}

public func generateMarkers() -> ForEach<[MarkerItem], MarkerItem.ID, Marker<Text>> {
ForEach(Array(selectedMapPoint.values.compactMap { $0 }), id: \.id) { markerItem in
Marker(item: markerItem.item)
public func addOriginDestinationData() {
switch originDestinationState {
case .origin:
originName = selectedMapPoint["origin"]??.item.name ?? "Location unknown"
originCoordinate = selectedMapPoint["origin"]??.item.placemark.coordinate
case .destination:
destinationName = selectedMapPoint["destination"]??.item.name ?? "Location unknown"
destinationCoordinate = selectedMapPoint["destination"]??.item.placemark.coordinate
}

checkAndFetchTripPlanner()
}

public func removeOriginDestinationData() {
switch originDestinationState {
case .origin:
originName = "Origin"
originCoordinate = nil
selectedMapPoint["origin"] = nil
case .destination:
destinationName = "Destination"
destinationCoordinate = nil
selectedMapPoint["destination"] = nil
}
}

Expand All @@ -126,6 +153,81 @@ public final class LocationManagerService: NSObject, ObservableObject {
currentCameraPosition = MapCameraPosition.item(item)
}

public func generateMarkers() -> ForEach<[MarkerItem], MarkerItem.ID, Marker<Text>> {
ForEach(Array(selectedMapPoint.values.compactMap { $0 }), id: \.id) { markerItem in
Marker(item: markerItem.item)
}
}

public func generateMapPolyline() -> MapPolyline? {
guard let itinerary = selectedItinerary else { return nil }

// Use steps to calculate the Location Coordinate
let coordinates = itinerary.legs.flatMap { leg in
leg.steps?.compactMap { step in
CLLocationCoordinate2D(latitude: step.lat, longitude: step.lon)
} ?? []
}

let coodinateExists = !coordinates.isEmpty

guard coodinateExists else { return nil }

return MapPolyline(coordinates: coordinates)
}

// MARK: - Trip Planner Methods

private func checkAndFetchTripPlanner() {
guard originCoordinate != nil,
destinationCoordinate != nil
else {
return
}

let fromPlace = formatCoordinate(originCoordinate)
let toPlace = formatCoordinate(destinationCoordinate)

isFetchingResponse = true

Task {
do {
let response = try await apiClient.fetchPlan(
fromPlace: fromPlace,
toPlace: toPlace,
time: getCurrentTimeFormatted(),
date: getFormattedTodayDate(),
mode: "TRANSIT,WALK",
arriveBy: false,
maxWalkDistance: 1000,
wheelchair: false
)
DispatchQueue.main.async {
self.planResponse = response
self.isFetchingResponse = false
}
} catch {
DispatchQueue.main.async {
self.tripPlannerErrorMessage = "Failed to fetch data: \(error.localizedDescription)"
self.isFetchingResponse = false
}
}
}
}

public func resetTripPlanner() {
planResponse = nil
selectedMapPoint = [
"origin": nil,
"destination": nil
]
destinationCoordinate = nil
originCoordinate = nil
originName = "Origin"
destinationName = "Destination"
selectedItinerary = nil
}

// MARK: - User Location Methods

public func checkIfLocationServicesIsEnabled() {
Expand Down Expand Up @@ -212,3 +314,30 @@ extension LocationManagerService: CLLocationManagerDelegate {
checkLocationAuthorization()
}
}

// MARK: - Service Extension

extension LocationManagerService {
func formatCoordinate(_ coordinate: CLLocationCoordinate2D?) -> String {
guard let coordinate else { return "" }
return String(format: "%.4f,%.4f", coordinate.latitude, coordinate.longitude)
}

func getFormattedTodayDate() -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
let today = Date()

return dateFormatter.string(from: today)
}

func getCurrentTimeFormatted() -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "h:mm a"
dateFormatter.amSymbol = "AM"
dateFormatter.pmSymbol = "PM"
let currentDate = Date()

return dateFormatter.string(from: currentDate)
}
}
25 changes: 24 additions & 1 deletion OTPKitDemo/MapView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,22 @@ public struct MapView: View {

@State private var position: MapCameraPosition = .userLocation(fallback: .automatic)

private var isPlanResponsePresented: Binding<Bool> {
Binding(
get: { locationManagerService.planResponse != nil },
set: { _ in }
)
}

public var body: some View {
ZStack {
MapReader { proxy in
Map(position: $locationManagerService.currentCameraPosition, interactionModes: .all) {
locationManagerService
.generateMarkers()
locationManagerService
.generateMapPolyline()
.stroke(.blue, lineWidth: 5)
}
.mapControls {
if !locationManagerService.isMapMarkingMode {
Expand All @@ -47,10 +57,23 @@ public struct MapView: View {
OriginDestinationSheetView()
.environmentObject(sheetEnvironment)
}
.sheet(isPresented: isPlanResponsePresented, content: {
TripPlannerSheetView()
.presentationDetents([.medium, .large])
})
}

if locationManagerService.isFetchingResponse {
ProgressView()
}

if locationManagerService.isMapMarkingMode {
MapMarkingView()

} else if locationManagerService.selectedItinerary != nil {
VStack {
Spacer()
TripPlannerView()
}
} else {
VStack {
Spacer()
Expand Down
Loading
Loading