Les traductions sont fournies par des outils de traduction automatique. En cas de conflit entre le contenu d'une traduction et celui de la version originale en anglais, la version anglaise prévaudra.
Utilisation de MapLibre Native SDK pour iOS avec Amazon Location Service
Utilisez MapLibreNative SDK pour iOS pour
The MapLibre Native SDK pour iOS est une bibliothèque basée sur Mapbox GL Native
Ce didacticiel explique comment intégrer le MapLibre Native SDK pour iOS à Amazon Location. L'exemple d'application de ce didacticiel est disponible dans le référentiel d'exemples Amazon Location Service sur GitHub
Création de l'application : initialisation
Pour initialiser votre application :
-
Créez un nouveau projet Xcode à partir du modèle d'application.
-
Sélectionnez SwiftUI pour son interface.
-
Sélectionnez l'application SwiftUI pour son cycle de vie.
-
Sélectionnez Swift pour sa langue.
Ajouter des MapLibre dépendances à l'aide de packages Swift
Pour ajouter une dépendance de package à votre projet Xcode :
-
Accédez à Fichier > Packages Swift > Ajouter une dépendance de package.
-
Entrez dans le référentiel URL :
https://github.com/maplibre/maplibre-gl-native-distribution
Note
Pour plus d'informations sur les packages Swift, voir Ajouter des dépendances de packages à votre application
sur Apple.com. -
Dans votre terminal, installez CocoaPods :
sudo gem install cocoapods
-
Accédez au répertoire du projet de votre application et initialisez le Podfile avec le gestionnaire de CocoaPods packages :
pod init
-
Ouvrez le Podfile à ajouter en
AWSCore
tant que dépendance :platform :ios, '12.0' target 'Amazon Location Service Demo' do use_frameworks! pod 'AWSCore' end
-
Téléchargez et installez les dépendances :
pod install --repo-update
-
Ouvrez l'espace de travail Xcode qui CocoaPods a créé :
xed .
Création de l'application : Configuration
Ajoutez les clés et valeurs suivantes à Info.plist pour configurer l'application :
Clé | Valeur |
---|---|
AWSRegion | us-east-1 |
IdentityPoolId | us-east- 1:54 f2ba88-9390-498d-aaa5-0d97fb7ca3bd |
MapName | ExampleMap |
Création de l'application : ContentView mise en page
Pour afficher la carte, modifiez ContentView.swift
:
-
Ajoutez un
MapView
qui affiche la carte. -
Ajoutez un
TextField
qui affiche l'attribution.
Cela définit également le point central initial de la carte.
import SwiftUI struct ContentView: View { @State private var attribution = "" var body: some View { MapView(attribution: $attribution) .centerCoordinate(.init(latitude: 49.2819, longitude: -123.1187)) .zoomLevel(12) .edgesIgnoringSafeArea(.all) .overlay( TextField("", text: $attribution) .disabled(true) .font(.system(size: 12, weight: .light, design: .default)) .foregroundColor(.black) .background(Color.init(Color.RGBColorSpace.sRGB, white: 0.5, opacity: 0.5)) .cornerRadius(1), alignment: .bottomTrailing) } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
Note
Vous devez indiquer l'attribution d'un mot ou d'un texte pour chaque fournisseur de données que vous utilisez, que ce soit sur votre application ou dans votre documentation. Les chaînes d'attribution sont incluses dans la réponse du descripteur de style sous les source.grabmaptiles.attribution
touches sources.esri.attribution
sources.here.attribution
, et. Lorsque vous utilisez les ressources Amazon Location avec des fournisseurs de données, assurez-vous de lire les conditions générales du service
Création de l'application : transformation des demandes
Créez un nouveau fichier Swift nommé AWSSignatureV4Delegate.swift
contenant la définition de classe suivante pour intercepter les AWS demandes et les signer à l'aide de Signature Version 4. Une instance de cette classe sera affectée en tant que délégué au stockage hors ligne, qui est également responsable de la réécritureURLs, dans la vue cartographique.
import AWSCore import Mapbox class AWSSignatureV4Delegate : NSObject, MGLOfflineStorageDelegate { private let region: AWSRegionType private let identityPoolId: String private let credentialsProvider: AWSCredentialsProvider init(region: AWSRegionType, identityPoolId: String) { self.region = region self.identityPoolId = identityPoolId self.credentialsProvider = AWSCognitoCredentialsProvider(regionType: region, identityPoolId: identityPoolId) super.init() } class func doubleEncode(path: String) -> String? { return path.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)? .addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) } func offlineStorage(_ storage: MGLOfflineStorage, urlForResourceOf kind: MGLResourceKind, with url: URL) -> URL { if url.host?.contains("amazonaws.com") != true { // not an AWS URL return url } // URL-encode spaces, etc. let keyPath = String(url.path.dropFirst()) guard let percentEncodedKeyPath = keyPath.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { print("Invalid characters in path '\(keyPath)'; unsafe to sign") return url } let endpoint = AWSEndpoint(region: region, serviceName: "geo", url: url) let requestHeaders: [String: String] = ["host": endpoint!.hostName] // sign the URL let task = AWSSignatureV4Signer .generateQueryStringForSignatureV4( withCredentialProvider: credentialsProvider, httpMethod: .GET, expireDuration: 60, endpoint: endpoint!, // workaround for https://github.com/aws-amplify/aws-sdk-ios/issues/3215 keyPath: AWSSignatureV4Delegate.doubleEncode(path: percentEncodedKeyPath), requestHeaders: requestHeaders, requestParameters: .none, signBody: true) task.waitUntilFinished() if let error = task.error as NSError? { print("Error occurred: \(error)") } if let result = task.result { var urlComponents = URLComponents(url: (result as URL), resolvingAgainstBaseURL: false)! // re-use the original path; workaround for https://github.com/aws-amplify/aws-sdk-ios/issues/3215 urlComponents.path = url.path // have Mapbox GL fetch the signed URL return (urlComponents.url)! } // fall back to an unsigned URL return url } }
Création de l'application : vue cartographique
La vue cartographique est chargée d'initialiser une instance du sous-jacent AWSSignatureV4Delegate
et de le configurerMGLMapView
, qui récupère les ressources et affiche la carte. Il gère également la propagation des chaînes d'attribution depuis la source du descripteur de style vers le. ContentView
Créez un nouveau fichier Swift nommé MapView.swift
contenant la struct
définition suivante :
import SwiftUI import AWSCore import Mapbox struct MapView: UIViewRepresentable { @Binding var attribution: String private var mapView: MGLMapView private var signingDelegate: MGLOfflineStorageDelegate init(attribution: Binding<String>) { let regionName = Bundle.main.object(forInfoDictionaryKey: "AWSRegion") as! String let identityPoolId = Bundle.main.object(forInfoDictionaryKey: "IdentityPoolId") as! String let mapName = Bundle.main.object(forInfoDictionaryKey: "MapName") as! String let region = (regionName as NSString).aws_regionTypeValue() // MGLOfflineStorage doesn't take ownership, so this needs to be a member here signingDelegate = AWSSignatureV4Delegate(region: region, identityPoolId: identityPoolId) // register a delegate that will handle SigV4 signing MGLOfflineStorage.shared.delegate = signingDelegate mapView = MGLMapView( frame: .zero, styleURL: URL(string: "https://maps.geo.\(regionName).amazonaws.com/maps/v0/maps/\(mapName)/style-descriptor")) _attribution = attribution } func makeCoordinator() -> Coordinator { Coordinator($attribution) } class Coordinator: NSObject, MGLMapViewDelegate { var attribution: Binding<String> init(_ attribution: Binding<String>) { self.attribution = attribution } func mapView(_ mapView: MGLMapView, didFinishLoading style: MGLStyle) { let source = style.sources.first as? MGLVectorTileSource let attribution = source?.attributionInfos.first self.attribution.wrappedValue = attribution?.title.string ?? "" } } // MARK: - UIViewRepresentable protocol func makeUIView(context: UIViewRepresentableContext<MapView>) -> MGLMapView { mapView.delegate = context.coordinator mapView.logoView.isHidden = true mapView.attributionButton.isHidden = true return mapView } func updateUIView(_ uiView: MGLMapView, context: UIViewRepresentableContext<MapView>) { } // MARK: - MGLMapView proxy func centerCoordinate(_ centerCoordinate: CLLocationCoordinate2D) -> MapView { mapView.centerCoordinate = centerCoordinate return self } func zoomLevel(_ zoomLevel: Double) -> MapView { mapView.zoomLevel = zoomLevel return self } }
L'exécution de cette application affiche une carte en plein écran dans le style de votre choix. Cet exemple est disponible dans le référentiel d'exemples Amazon Location Service sur GitHub