mapbox sdk
MapBox is a location data platform for mobile and web applications. They provide building blocks to add location features like maps, search, and navigation into any app you create. For this app, we’re going to use their iOS SDK in order to show basic point annotations on their Map.
MapBox是用于移动和Web应用程序的位置数据平台。 它们提供了构建基块,可以将位置功能(例如地图,搜索和导航)添加到您创建的任何应用程序中。 对于此应用程序,我们将使用其iOS SDK以便在其地图上显示基本点注释。
安装Mapbox SDK (Installing the Mapbox SDK)
First we’re going to be adding the Mapbox SDK to our project. The best way to add the SDK to the app is through CocoaPods.
首先,我们将Mapbox SDK添加到我们的项目中。 将SDK添加到应用程序的最佳方法是通过CocoaPods 。
If you don’t already have CocoaPods installed on your machine then open up a terminal and run the following command.
sudo gem install cocoapods
如果您的计算机上尚未安装CocoaPods ,请打开终端并运行以下命令。
sudo gem install cocoapods
Open up a terminal and navigate to your project directory. You want to be in the folder that holds your <project_name>.xcodeproj
. Then run the following command to initialize Cocoapods with your project.
打开一个终端并导航到您的项目目录。 您希望位于保存<project_name>.xcodeproj
的文件夹中。 然后运行以下命令以用项目初始化Cocoapods 。
pod init
Once complete there should be a new file created inside the directory called Podfile
. This is the file we'll edit to add the Mapbox SDK Cocoapod to our app. Open that file up and add the following line underneath the comment # Pods for <project_name>
. Remember to save your file after making your edits.
完成后,应该在目录Podfile
创建一个新文件。 我们将编辑该文件,以将Mapbox SDK Cocoapod添加到我们的应用中。 打开该文件,并在注释# Pods for <project_name>
下添加以下行。 记住在进行编辑后保存文件。
pod 'Mapbox-iOS-SDK', '~> 5.9'
Now head back to your terminal and run the following command to install the Pod. This may take a few minutes to download and install the SDK to your project.
现在回到您的终端并运行以下命令来安装Pod。 下载SDK并将其安装到您的项目可能需要几分钟。
pod install
Once finished close your Xcode project and reopen it. Instead of opening the <project_name>.xcodeproj
, open up the <project_name>.xcworkspace
file. This is the file we'll be using from now on to edit our project. It does all of the work of including the Mapbox SDK in our project.
完成后,关闭Xcode项目并重新打开它。 不用打开<project_name>.xcodeproj
,而是打开<project_name>.xcworkspace
文件。 这是我们从现在开始将用于编辑项目的文件。 它完成了将Mapbox SDK包含在我们的项目中的所有工作。
设置API令牌和权限 (Setup API Token and Permissions)
In order to use the Mapbox SDK in your app you’ll need an api token. Fortunately this is free.
为了在您的应用中使用Mapbox SDK,您需要一个api令牌。 幸运的是,这是免费的。
Create an account on Mapbox.com
在Mapbox.com上创建一个帐户
- Navigate to your account home 导航到您的帐户首页
Scroll to bottom where it says “Access Tokens”. It will show you your default public token which you can use for this app.
滚动到底部的“访问令牌” 。 它将显示您可以用于此应用程序的默认公共令牌。
![Image for post](https://miro.medium.com/max/9999/0*j_YWpBuP-8JAOOMC.png)
Next we nee to copy the token to your
Info.plist
file. Create a row with the keyMGLMapboxAccessToken
, and the value should be your access token.接下来,我们将标记复制到您的
Info.plist
文件中。 使用键MGLMapboxAccessToken
创建一个行,该值应该是您的访问令牌。Create another row in your
Info.plist
file with the keyNSLocationWhenInUseUsageDescription
and the valueShow user location on map.
使用键
NSLocationWhenInUseUsageDescription
和值为Show user location on map.
Info.plist
文件中创建另一行Show user location on map.
![Image for post](https://miro.medium.com/max/9999/0*HzJDSPJ9qIXW4QkS.png)
Info.plist
to include access token and usage description
Info.plist
以包括访问令牌和使用说明
添加地图 (Adding a Map)
In order for us to to use Mapbox’s MGLMapView
in our app, we'll need to create a UIViewRepresentable
(Apple's Documentation).
为了使我们能够在我们的应用程序中使用Mapbox的MGLMapView
,我们需要创建一个UIViewRepresentable
( Apple的文档 )。
MapboxMap
(MapboxMap
)
import SwiftUI
import Mapbox
struct MapboxMap: UIViewRepresentable {
private let mapView: MGLMapView = MGLMapView(frame: .zero, styleURL: MGLStyle.lightStyleURL)
func makeUIView(context: Context) -> MGLMapView {
mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
mapView.setCenter(CLLocationCoordinate2D(latitude: 59.31, longitude: 18.06), zoomLevel: 9, animated: false)
mapView.delegate = context.coordinator
return mapView
}
func updateUIView(_ uiView: MGLMapView, context: Context) {}
}
Then navigate to your ContentView.swift
file and replace the Text
placeholder with a MapboxMap
like this:
然后导航到您的ContentView.swift
文件,并将Text
占位符替换为MapboxMap
如下所示:
struct ContentView: View {
var body: some View {
MapboxMap()
}
}
![Image for post](https://miro.medium.com/max/9999/0*7r9ympGNZuYtrI13.png)
MapboxMap
MapboxMap
运行我们的应用
添加注释 (Adding Annotations)
Let’s continue with the development of our MapboxMap
struct. We're going to add a coordinator to allow us to interface with the MGLMapVieDelegate. This will allow us to do things such as plot annotations on the map.
让我们继续开发MapboxMap
结构。 我们将添加一个协调器,以使我们能够与MGLMapVieDelegate交互。 这将使我们能够做一些事情,例如在地图上标出注释。
创建协调员 (Create a Coordinator)
Inside your MapboxMap
struct define the class Coordinator
which inherits from NSObject
and implements the MGLMapViewDelegate
.
在您的MapboxMap
结构中定义一个类Coordinator
,该类从NSObject
继承并实现MGLMapViewDelegate
。
class Coordinator: NSObject, MGLMapViewDelegate {
}
Next we need to implement the MGLMapViewDelegate
functions which allow us to add annotations.
接下来,我们需要实现MGLMapViewDelegate
函数,该函数允许我们添加注释。
class Coordinator: NSObject, MGLMapViewDelegate {
func mapView(_ mapView: MGLMapView, viewFor annotation: MGLAnnotation) -> MGLAnnotationView? {
return nil
}
func mapView(_ mapView: MGLMapView, annotationCanShowCallout annotation: MGLAnnotation) -> Bool {
return true
}
}
实施makeCoordinator
(Implement makeCoordinator
)
Inside your MapboxMap
struct we need to implement the makeCoordinator()
function and tell it to use our new coordinator. SwiftUI calls this makeCoordinator()
method before makeUIView(context:)
, so that you have access to the coordinator object when configuring your view.
在您的MapboxMap
结构中,我们需要实现makeCoordinator()
函数并告诉它使用我们的新协调器。 SwiftUI在makeUIView(context:)
之前调用此makeCoordinator()
方法,以便您在配置视图时可以访问协调器对象。
You can use this coordinator to implement common Cocoa patterns, such as delegates, data sources, and responding to user events via target-action.
您可以使用此协调器来实现常见的Cocoa模式,例如委托,数据源,以及通过target-action响应用户事件。
func makeCoordinator() -> MapboxMap.Coordinator {
return Coordinator()
}
Then update the makeUIView(context:)
function to set our the mapView
delegate as the coordinator.
然后更新makeUIView(context:)
函数以将我们的mapView
委托设置为协调器。
func makeUIView(context: Context) -> MGLMapView {
mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
mapView.setCenter(CLLocationCoordinate2D(latitude: 59.31, longitude: 18.06), zoomLevel: 9, animated: false)
mapView.delegate = context.coordinator
return mapView
}
存储注释的坐标 (Storing Coordinates for Annotations)
At the top of your MapboxMap
struct we need to create a variable to hold the coordinates for our annotations.
在MapboxMap
结构的顶部,我们需要创建一个变量来保存注释的坐标。
@Binding var locations:[CLLocationCoordinate2D]
Now let’s create a function to add these coordinates as annotations to our map. The function below takes to the current annotations on the map and builds a new array of Point Annotations to be placed in accordance with the locations currently stored in our locations
variable.
现在,让我们创建一个函数,以将这些坐标添加为地图的注释。 下面的函数将获取地图上的当前注释,并根据当前存储在我们的locations
变量中的locations
构建一个新的Point Annotations数组。
private func updateAnnotations() {
if let currentAnnotations = mapView.annotations {
mapView.removeAnnotations(currentAnnotations)
}
mapView.addAnnotations(locations.map({ (coord) -> MGLPointAnnotation in
let annotation = MGLPointAnnotation()
annotation.coordinate = coord
return annotation
}))
}
Now all we need to do is call is in our updateUIView(uiview:,context:)
function.
现在,我们需要做的就是在我们的updateUIView(uiview:,context:)
函数中进行调用。
func updateUIView(_ uiView: MGLMapView, context: Context) {
updateAnnotations()
}
运行一个例子 (Running an Example)
Head back to ContentView.swift
and try running with the following code.
回到ContentView.swift
并尝试使用以下代码运行。
struct ContentView: View {
@State var locations:[CLLocationCoordinate2D] = [CLLocationCoordinate2D(latitude: 59.3293, longitude: 18.0686)]
var body: some View {
MapboxMap(locations: $locations)
.edgesIgnoringSafeArea(.vertical)
}
}
![Image for post](https://miro.medium.com/max/9999/0*KL8ZNmP1No2jD-9t.png)
支持未来的教程! (Support Future Tutorials!)
Please consider subscribing using this link. If you aren’t reading this on TrailingClosure.com, please come check us out sometime!
请考虑使用此链接进行订阅。 如果您没有在TrailingClosure.com上阅读此书 ,请随时联系我们!
If you’ve built something using this tutorial, send us pics! Find us on Twitter @TrailingClosure, or email us at howdy@TrailingClosure.com
如果您使用本教程构建了一些东西,请给我们发送图片! 在Twitter @TrailingClosure上找到我们,或通过howdy@TrailingClosure.com给我们发送电子邮件
翻译自: https://levelup.gitconnected.com/swiftui-integrating-the-mapbox-sdk-5a8098708b3c
mapbox sdk