我正在创建一个 iOS 应用程序,我想让用户能够选择打开哪个地图应用程序(Apple 地图或 Google 地图)。对于 Google 地图,他们建议使用地图网址,这是更安全、更可靠的路线。酷。
在我的应用程序中,用户已经能够点击地图上的位置(我正在使用 Apple 地图框架)。所以,我已经可以访问坐标、名称和地址。我可以仅使用带有此信息的地图网址,但是 Google 地图将在该确切位置仅显示一个图钉,而这是我不想要的。通过提供 PlaceID,Google 地图将打开并显示所选的商家,这正是我想要的。
我的问题是检索 PlaceID 最简单的方法是什么?我可以只使用坐标进行 API 调用并获取包含 placeID 的响应吗?然后,在我构建的通用地图网址中使用该 PlaceID 来在该营业地点打开 Google 地图?
或者也许我让整个事情变得复杂了?
查看 Google 的文档。我尝试过只使用坐标。我将尝试使用坐标加上带有企业名称的查询。只是想提供最好的体验。在我的应用程序中,我想坚持使用 Apple 地图,但我也希望用户可以选择在他们喜欢的地图服务中打开一个位置(如果他们需要路线和其他信息)。
我想我已经找到了一条令我相当满意的方法。我最终所做的是针对我传递的名称+地址的查询。这使得 Google 地图无法找到更多靠近所提供坐标的同名位置。基本上,我只是向查询添加更多详细信息。然后我使用
center
参数传入坐标。
看起来像这样:
快速说明:
selectedSearchResult
是来自 MapKit 的 MKMapItem
placemark
是 CLPlacemark
// Function that builds the url
private func googleMapsUrl() -> URL? {
guard let mapItem = selectedSearchResult else { return nil }
let coordinate = mapItem.placemark.coordinate
let address = mapItem.placemark.title ?? ""
let name = mapItem.name ?? ""
let queryItems: [URLQueryItem] = [
.init(name: "api", value: "1"),
.init(name: "query", value: "\(name) \(address)"),
.init(name: "center", value: "\(coordinate.latitude) \(coordinate.longitude)")
]
var components = URLComponents(string: "https://www.google.com/maps/search/")
components?.queryItems = queryItems
return components?.url
}
从 SwiftUI 内部调用它
Button
,如下所示:
if let url = googleMapsUrl(), UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url) { success in
if success {
print("Successfully opened url: \(url.absoluteString)")
} else {
print("Failed to open url: \(url.absoluteString)")
}
}
}
到目前为止,效果非常好!我也会处理错误。我可以点击任何
MKMapItem
,获取名称、地址和坐标,然后将所有这些一起使用来形成查询,然后 Google 地图会直接打开该位置,其中包含名称和所有内容。它不仅仅在地图上显示一个图钉,这正是我试图避免的——由“位置搜索”部分下的文档进行了解释,其中他们使用 CenturyLink Field 作为示例。