mapbox sdk_swiftui集成mapbox sdk

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令牌。 幸运的是,这是免费的。

  1. Create an account on Mapbox.com

    Mapbox.com上创建一个帐户

  2. Navigate to your account home

    导航到您的帐户首页
  3. 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
Create your Access Token on Mapbox
在Mapbox上创建访问令牌
  1. Next we nee to copy the token to your Info.plist file. Create a row with the key MGLMapboxAccessToken, and the value should be your access token.

    接下来,我们将标记复制到您的Info.plist文件中。 使用键MGLMapboxAccessToken创建一个行,该值应该是您的访问令牌。

  2. Create another row in your Info.plist file with the key NSLocationWhenInUseUsageDescription and the value Show user location on map.

    使用键NSLocationWhenInUseUsageDescription和值为Show user location on map. Info.plist文件中创建另一行Show user location on map.

Image for post
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
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
Annotation on Mapbox Map using SwiftUI
使用SwiftUI在Mapbox地图上进行注释

支持未来的教程! (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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值