Stadia Maps SwiftUI 自动补全搜索

此软件包可帮助您轻松地向 SwiftUI 应用程序添加地理位置自动补全搜索功能。

Screenshot

安装

Xcode 的用户界面经常更改,但您通常可以使用“文件”菜单中的选项将软件包添加到您的项目中。然后,您需要粘贴存储库 URL 进行搜索:https://github.com/stadiamaps/swiftui-autocomplete-search。有关 Apple 提供的最新详细说明,请参阅 https://developer.apple.com/documentation/xcode/adding-package-dependencies-to-your-app

获取 API 密钥

您需要 API 密钥才能使用此视图。

您可以在此处免费创建 API 密钥(无需信用卡)。

请注意,虽然自动补全搜索在免费层级中可用,但在提交时进行的深度搜索以及对高级功能(如缺失地址插值)的支持仅在付费订阅中才可用。

使用 SwiftUI 视图

import StadiaMapsAutocompleteSearch
let stadiaMapsAPIKey = "YOUR-API-KEY"  // Replace with your API key

// Somewhere in your view body....
AutocompleteSearch(apiKey: stadiaMapsAPIKey, userLocation: userLocation.clLocation) { selection in
    // Do something with the selection.
    // For example, you might do something like this to start navigation
    // in an app using Ferrostar (https://github.com/stadiamaps/ferrostar).
    Task {
        do {
            routes = try await ferrostarCore.getRoutes(initialLocation: userLocation, waypoints: [Waypoint(coordinate: GeographicCoordinate(lat: selection.geometry.coordinates[1], lng: selection.geometry.coordinates[0]), kind: .break)])

            try ferrostarCore.startNavigation(route: routes!.first!)
            errorMessage = nil
        } catch {
            errorMessage = "Error: \(error)"
        }
    }
}

自定义结果视图

不喜欢默认的搜索结果视图?您可以将其替换为任何 SwiftUI 视图,从而自定义列表项视图。

AutocompleteSearch(apiKey: previewApiKey, onResultSelected: { selection in
    // TODO: Result selection handler
}) { feature, _ in
    // This custom view builder will have a classic table cell layout,
    // where the image is always a laser burst from SFSymbols.
    HStack {
        Image(systemName: "laser.burst")
        Text(feature.properties?.name ?? "<No name>")
    }
}