set up map sdk and reusable map view component (#1062)

* added map sdk with basic permission and static view

* add location annotation

* create dedicate service for MapTiler URLs

* manage error for MapLibre component

* add error to new Alert item
This commit is contained in:
Flescio
2023-06-14 11:08:36 +02:00
committed by GitHub
parent 1c2964c86d
commit 3374ebb48d
18 changed files with 715 additions and 23 deletions
@@ -170,7 +170,20 @@ final class AppSettings {
// MARK: - Other
let permalinkBaseURL = URL(staticString: "https://matrix.to")
// MARK: - Maps
// maptiler dynamic map urls
let lightTileMapStyleURL = "https://api.maptiler.com/maps/9bc819c8-e627-474a-a348-ec144fe3d810/style.json"
let darkTileMapStyleURL = "https://api.maptiler.com/maps/dea61faf-292b-4774-9660-58fcef89a7f3/style.json"
// maptiler api key
let mapTilerApiKey = "fU3vlMsMn4Jb6dnEIFsx"
// maptiler static map urls
let lightTileStaticMapStyleURL = "https://api.maptiler.com/maps/9bc819c8-e627-474a-a348-ec144fe3d810/{z}/{x}/{y}.png"
let darkTileStaticMapStyleURL = "https://api.maptiler.com/maps/dea61faf-292b-4774-9660-58fcef89a7f3/{z}/{x}/{y}.png"
// MARK: - Feature Flags
// MARK: Start Chat
@@ -51,6 +51,7 @@ struct ErrorAlertItem: AlertItem {
var action: () -> Void
}
var error: Error
var title = L10n.commonError
var message = L10n.errorUnknown
var cancelAction = Action(title: L10n.actionOk, action: { })
@@ -0,0 +1,23 @@
//
// Copyright 2023 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
extension MapTilerStyleBuilder {
init(appSettings: AppSettings) {
self.init(lightURL: appSettings.lightTileMapStyleURL, darkURL: appSettings.darkTileMapStyleURL, key: appSettings.mapTilerApiKey)
}
}
@@ -0,0 +1,100 @@
//
// Copyright 2023 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import Mapbox
import SwiftUI
/// Base class to handle a map annotation
class LocationAnnotation: NSObject, MGLAnnotation {
// MARK: - Properties
// Title property is needed to enable annotation selection and callout view showing
var title: String?
let coordinate: CLLocationCoordinate2D
// MARK: - Setup
init(coordinate: CLLocationCoordinate2D) {
self.coordinate = coordinate
super.init()
}
}
/// POI map annotation
class PinLocationAnnotation: LocationAnnotation { }
class LocationAnnotationView: MGLUserLocationAnnotationView {
private enum Constants {
static let defaultFrame = CGRect(x: 0, y: 0, width: 46, height: 46)
}
// MARK: - Setup
override init(annotation: MGLAnnotation?, reuseIdentifier: String?) {
super.init(annotation: annotation, reuseIdentifier:
reuseIdentifier)
frame = Constants.defaultFrame
}
convenience init(userPinLocationAnnotation: MGLAnnotation) {
self.init(annotation: userPinLocationAnnotation, reuseIdentifier: "userPinLocation")
addUserView()
}
convenience init(pinLocationAnnotation: PinLocationAnnotation) {
self.init(annotation: pinLocationAnnotation, reuseIdentifier: nil)
addPinView()
}
@available(*, unavailable)
required init?(coder: NSCoder) {
fatalError()
}
// MARK: - Private
private func addUserView() {
guard let pinView = UIHostingController(rootView: Image(systemName: "circle.fill")
.resizable()
.foregroundColor(.element.accent)).view else {
return
}
addMarkerView(pinView)
}
private func addPinView() {
guard let pinView = UIHostingController(rootView: Image(systemName: "mappin")
.resizable()
.foregroundColor(.element.accent)).view else {
return
}
addMarkerView(pinView)
}
private func addMarkerView(_ markerView: UIView) {
markerView.backgroundColor = .clear
addSubview(markerView)
markerView.frame = bounds
}
}
@@ -0,0 +1,162 @@
//
// Copyright 2023 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Combine
import Mapbox
import SwiftUI
struct MapLibreMapView: UIViewRepresentable {
// MARK: - Constants
private enum Constants {
static let mapZoomLevel = 15.0
}
// MARK: - Properties
@Environment(\.colorScheme) private var colorScheme
let builder: MapTilerStyleBuilderProtocol
/// Behavior mode of the current user's location, can be hidden, only shown and shown following the user
var showsUserLocationMode: ShowUserLocationMode = .hide
/// Bind view errors if any
let error: Binding<MapLibreError?>
// MARK: - UIViewRepresentable
func makeUIView(context: Context) -> MGLMapView {
let mapView = makeMapView()
mapView.delegate = context.coordinator
return mapView
}
func updateUIView(_ mapView: MGLMapView, context: Context) {
mapView.removeAllAnnotations()
if colorScheme == .dark {
mapView.styleURL = builder.dynamicMapURL(for: .dark)
} else {
mapView.styleURL = builder.dynamicMapURL(for: .light)
}
showUserLocation(in: mapView)
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
// MARK: - Private
private func makeMapView() -> MGLMapView {
let mapView = MGLMapView(frame: .zero, styleURL: colorScheme == .dark ? builder.dynamicMapURL(for: .dark) : builder.dynamicMapURL(for: .light))
mapView.logoView.isHidden = true
mapView.attributionButton.isHidden = true
mapView.zoomLevel = Constants.mapZoomLevel
showUserLocation(in: mapView)
return mapView
}
private func showUserLocation(in mapView: MGLMapView) {
switch showsUserLocationMode {
case .follow:
mapView.showsUserLocation = true
mapView.userTrackingMode = .follow
case .show:
mapView.showsUserLocation = true
mapView.userTrackingMode = .none
case .hide:
mapView.showsUserLocation = false
mapView.userTrackingMode = .none
}
}
}
// MARK: - Coordinator
extension MapLibreMapView {
class Coordinator: NSObject, MGLMapViewDelegate, UIGestureRecognizerDelegate {
// MARK: - Properties
var mapLibreView: MapLibreMapView
// MARK: - Setup
init(_ mapLibreView: MapLibreMapView) {
self.mapLibreView = mapLibreView
}
// MARK: - MGLMapViewDelegate
func mapView(_ mapView: MGLMapView, viewFor annotation: MGLAnnotation) -> MGLAnnotationView? {
if let pinLocationAnnotation = annotation as? PinLocationAnnotation {
return LocationAnnotationView(pinLocationAnnotation: pinLocationAnnotation)
} else if annotation is MGLUserLocation {
return LocationAnnotationView(userPinLocationAnnotation: annotation)
}
return nil
}
func mapViewDidFailLoadingMap(_ mapView: MGLMapView, withError error: Error) {
mapLibreView.error.wrappedValue = .failedLoadingMap
}
func mapView(_ mapView: MGLMapView, didUpdate userLocation: MGLUserLocation?) { }
func mapView(_ mapView: MGLMapView, didChangeLocationManagerAuthorization manager: MGLLocationManager) {
guard mapView.showsUserLocation else {
return
}
switch manager.authorizationStatus {
case .denied, .restricted:
mapLibreView.error.wrappedValue = .invalidLocationAuthorization
default:
break
}
}
func mapView(_ mapView: MGLMapView, regionDidChangeAnimated animated: Bool) { }
// MARK: Callout
func mapView(_ mapView: MGLMapView, annotationCanShowCallout annotation: MGLAnnotation) -> Bool {
false
}
// MARK: UIGestureRecognizer
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
gestureRecognizer is UIPanGestureRecognizer
}
}
}
// MARK: - MGLMapView convenient methods
private extension MGLMapView {
func removeAllAnnotations() {
guard let annotations else {
return
}
removeAnnotations(annotations)
}
}
@@ -0,0 +1,40 @@
//
// Copyright 2023 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
/*
Behavior mode of the current user's location, can be hidden, only shown and shown following the user
*/
enum ShowUserLocationMode {
/// this mode will show the user pin in map and track him, panning the map automatically
case follow
/// this mode will show the user pin in map
case show
/// this mode will not show the user pin in map
case hide
}
enum MapTilerStyle {
case light
case dark
}
enum MapLibreError: Error {
case failedLoadingMap
case failedLocatingUser
case invalidLocationAuthorization
}
@@ -0,0 +1,29 @@
//
// Copyright 2023 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
struct MapTilerAuthorization {
private let key: String
init(key: String) {
self.key = key
}
func authorizateURL(_ url: URL) -> URL {
url.appending(queryItems: [URLQueryItem(name: "key", value: key)])
}
}
@@ -0,0 +1,41 @@
//
// Copyright 2023 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
protocol MapTilerStyleBuilderProtocol {
func dynamicMapURL(for style: MapTilerStyle) -> URL?
}
struct MapTilerStyleBuilder: MapTilerStyleBuilderProtocol {
let lightURL: String
let darkURL: String
let key: String
func dynamicMapURL(for style: MapTilerStyle) -> URL? {
let path: String
switch style {
case .light:
path = lightURL
case .dark:
path = darkURL
}
guard let url = URL(string: path) else { return nil }
let authorization = MapTilerAuthorization(key: key)
return authorization.authorizateURL(url)
}
}
@@ -0,0 +1,45 @@
//
// Copyright 2023 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
enum LocationSharingViewError: Error {
case failedSharingLocation
case mapError(MapLibreError)
}
enum StaticLocationScreenViewModelAction { }
struct StaticLocationScreenViewState: BindableState {
var bindings = StaticLocationScreenBindings()
}
struct StaticLocationScreenBindings {
/// Information describing the currently displayed alert.
var mapError: MapLibreError? {
get {
errorAlert?.error as? MapLibreError
}
set {
errorAlert = newValue.map { ErrorAlertItem(error: $0) }
}
}
/// Information describing the currently displayed alert.
var errorAlert: ErrorAlertItem?
}
enum StaticLocationScreenViewAction { }
@@ -0,0 +1,39 @@
//
// Copyright 2023 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Combine
import SwiftUI
struct StaticLocationScreenCoordinatorParameters { }
enum StaticLocationScreenCoordinatorAction { }
final class StaticLocationScreenCoordinator: CoordinatorProtocol {
let parameters: StaticLocationScreenCoordinatorParameters
let viewModel: StaticLocationScreenViewModelProtocol
init(parameters: StaticLocationScreenCoordinatorParameters) {
self.parameters = parameters
viewModel = StaticLocationScreenViewModel()
}
// MARK: - Public
func toPresentable() -> AnyView {
AnyView(StaticLocationScreen(context: viewModel.context))
}
}
@@ -0,0 +1,32 @@
//
// Copyright 2023 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Combine
import Foundation
typealias StaticLocationScreenViewModelType = StateStoreViewModel<StaticLocationScreenViewState, StaticLocationScreenViewModelAction>
class StaticLocationScreenViewModel: StaticLocationScreenViewModelType, StaticLocationScreenViewModelProtocol {
private let actionsSubject: PassthroughSubject<StaticLocationScreenViewModelAction, Never> = .init()
var actions: AnyPublisher<StaticLocationScreenViewModelAction, Never> {
actionsSubject.eraseToAnyPublisher()
}
init() {
super.init(initialViewState: StaticLocationScreenViewState())
}
}
@@ -0,0 +1,23 @@
//
// Copyright 2023 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Combine
@MainActor
protocol StaticLocationScreenViewModelProtocol {
var actions: AnyPublisher<StaticLocationScreenViewModelAction, Never> { get }
var context: StaticLocationScreenViewModelType.Context { get }
}
@@ -0,0 +1,53 @@
//
// Copyright 2023 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import SwiftUI
struct StaticLocationScreen: View {
@ObservedObject var context: StaticLocationScreenViewModel.Context
private let builder = MapTilerStyleBuilder(appSettings: ServiceLocator.shared.settings)
var body: some View {
NavigationView {
mapView
.ignoresSafeArea(.all, edges: [.bottom])
.navigationBarTitleDisplayMode(.inline)
.errorAlert(item: $context.errorAlert)
}
}
var mapView: MapLibreMapView {
MapLibreMapView(builder: builder,
showsUserLocationMode: .follow,
error: $context.mapError)
}
}
// MARK: - Previews
struct StaticLocationScreenViewer_Previews: PreviewProvider {
static let viewModel = {
let viewModel = StaticLocationScreenViewModel()
return viewModel
}()
static var previews: some View {
NavigationView {
StaticLocationScreen(context: viewModel.context)
}
}
}
@@ -55,8 +55,8 @@ class RoomMemberDetailsScreenViewModel: RoomMemberDetailsScreenViewModelType, Ro
switch result {
case .success:
state.details.isIgnored = true
case .failure:
state.bindings.errorAlert = .init()
case .failure(let error):
state.bindings.errorAlert = .init(error: error)
}
}
@@ -68,8 +68,8 @@ class RoomMemberDetailsScreenViewModel: RoomMemberDetailsScreenViewModelType, Ro
switch result {
case .success:
state.details.isIgnored = false
case .failure:
state.bindings.errorAlert = .init()
case .failure(let error):
state.bindings.errorAlert = .init(error: error)
}
}
}