本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
将适用于 iOS 的 MapLibre GL Native SDK 与亚马逊Location Service 一起使用
使用适用于 iOS 的MapLibre GL 原生 SDK
适用于 iOS 的 MapLibre GL Native SDK 是一个基于 Mapbox GL Nat
本教程介绍如何将适用于 iOS 的 MapLibre GL Native SDK 与亚马逊位置集成。本教程的示例应用程序作为亚马逊Location Service 示例存储库的一部分提供GitHub
构建应用程序:初始化
要初始化应用程序,请执行以下操作:
-
从应用程序模板创建一个新的 Xcode 项目。
-
选择 SwiftUI 作为其接口。
-
选择 SwiftUI 应用程序作为其生命周期。
-
选择 Swift 作为其语言。
使用 Swift 包添加 MapLibre依赖关系
要向您的 Xcode 项目添加包依赖关系,请执行以下操作:
-
导航到 “文件” > “Swift 软件包” > “添加Package 依赖关系”。
-
输入存储库 URL:
https://github.com/maplibre/maplibre-gl-native-distribution
注意 有关 Swift 包的更多信息,请参阅 Apple.com 上为应用程序添加Package 依赖关系
-
在您的终端中,安装 CocoaPods:
sudo gem install cocoapods
-
导航到应用程序的项目目录并使用 CocoaPods 包管理器初始化 Podfile:
pod init
-
打开 P odfile 将其添加
AWSCore
为依赖项:platform :ios, '12.0' target 'Amazon Location Service Demo' do use_frameworks! pod 'AWSCore' end
-
下载并安装依赖项:
pod install --repo-update
-
打开 CocoaPods 创建以下内容的 Xcode 工作区:
xed .
构建应用程序:配置
将以下键和值添加到 Info.plis t 以配置应用程序:
键 | 值 |
---|---|
AWSRegion | us-east-1 |
IdentityPoolId | us-east-1:54 f2ba88-9390-498d-aaa5-0d97fb7ca3bd |
MapName | ExampleMap |
构建应用程序: ContentView 布局
要渲染地图,请编辑ContentView.swift
:
-
添加
MapView
用于渲染地图的。 -
添加显示
TextField
归因的。
这也会设置地图的初始中心点。
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() } }
构建应用程序:请求转换
创建一个名为的新 Swift 文件,AWSSignatureV4Delegate.swift
其中包含以下类定义,以拦截 AWS 请求并使用签名版本 4 对请求进行签名。该类的实例将被指定为离线存储委托人,该委托还负责在地图视图中重写 URL。
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 } }
构建应用程序:地图视图
Map View 负责初始化实例AWSSignatureV4Delegate
并配置底层实例MGLMapView
,后者获取资源并呈现地图。它还负责将归因字符串从样式描述符的来源传播回到ContentView
。
创建一个名为的新 Swift 文件,MapView.swift
其中包含以下struct
定义:
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 } }
运行此应用程序以您选择的样式显示全屏地图。此示例作为亚马逊Location Service 示例存储库的一部分提供GitHub