使用Google Maps SDK for iOS开发Swift应用:如何获取骑行与公交信息?
嘿,我来帮你搞定这个问题!你已经成功开启了交通图层,接下来要实现骑行和公交信息的展示与获取,Google Maps SDK其实提供了很直接的方案,分两部分给你拆解:
一、获取骑行信息
1. 快速显示骑行图层
Google Maps SDK内置了专门的骑行图层,可以一键开启,直接在地图上展示自行车道、骑行专用路线等基础设施:
import GoogleMaps // 在你的地图视图控制器中添加这段代码 let bikeLayer = GMSBicyclingLayer() bikeLayer.map = mapView // mapView是你的GMSMapView实例对象
2. 获取骑行路线规划
如果需要生成从起点到终点的具体骑行路线,就得用到Google Directions API(SDK的图层仅展示静态骑行设施,路线规划需要调用API)。注意要先在Google Cloud项目中启用Directions API,并准备好有效的API密钥。
示例代码(用URLSession发起请求并解析路线):
func fetchBikeRoute(from origin: CLLocationCoordinate2D, to destination: CLLocationCoordinate2D) { let apiKey = "*你的Google API密钥*" let originStr = "\(origin.latitude),\(origin.longitude)" let destinationStr = "\(destination.latitude),\(destination.longitude)" guard let requestUrl = URL(string: "https://maps.googleapis.com/maps/api/directions/json?origin=\(originStr)&destination=\(destinationStr)&mode=bicycling&key=\(apiKey)") else { print("无效的请求URL") return } URLSession.shared.dataTask(with: requestUrl) { data, _, error in guard let data = data, error == nil else { print("请求失败:\(error?.localizedDescription ?? "未知错误")") return } do { // 解析返回的JSON数据,提取路线信息 if let json = try JSONSerialization.jsonObject(with: data) as? [String: Any], let routes = json["routes"] as? [[String: Any]], let firstRoute = routes.first, let polylineDict = firstRoute["overview_polyline"] as? [String: Any], let polylineStr = polylineDict["points"] as? String { // 将路线绘制到地图上 let routePath = GMSPath(fromEncodedPath: polylineStr) let routePolyline = GMSPolyline(path: routePath) routePolyline.strokeColor = .systemBlue routePolyline.strokeWidth = 3.0 routePolyline.map = self.mapView // 你还可以解析路线的距离、预计耗时等信息,按需展示给用户 } } catch { print("JSON解析失败:\(error.localizedDescription)") } }.resume() }
二、获取公交信息
1. 显示公交图层
和骑行图层类似,SDK提供了公交专用图层,开启后会展示公交路线、站点、地铁线路等公共交通设施:
let transitLayer = GMSTransitLayer() transitLayer.map = mapView
2. 获取公交路线规划与实时信息
公交路线规划
同样依赖Directions API,只需将请求参数mode设为transit即可获取换乘方案:
func fetchTransitRoute(from origin: CLLocationCoordinate2D, to destination: CLLocationCoordinate2D) { let apiKey = "*你的Google API密钥*" let originStr = "\(origin.latitude),\(origin.longitude)" let destinationStr = "\(destination.latitude),\(destination.longitude)" guard let requestUrl = URL(string: "https://maps.googleapis.com/maps/api/directions/json?origin=\(originStr)&destination=\(destinationStr)&mode=transit&key=\(apiKey)") else { print("无效的请求URL") return } URLSession.shared.dataTask(with: requestUrl) { data, _, error in guard let data = data, error == nil else { print("请求失败:\(error?.localizedDescription ?? "未知错误")") return } do { if let json = try JSONSerialization.jsonObject(with: data) as? [String: Any], let routes = json["routes"] as? [[String: Any]], let firstRoute = routes.first { // 解析公交换乘的详细步骤(比如步行到站点、乘坐的公交线路、换乘点等) if let legs = firstRoute["legs"] as? [[String: Any]], let firstLeg = legs.first { if let steps = firstLeg["steps"] as? [[String: Any]] { for step in steps { if let transitDetails = step["transit_details"] as? [String: Any] { let lineInfo = transitDetails["line"] as? [String: Any] let lineName = lineInfo?["name"] as? String ?? "未知线路" let headsign = transitDetails["headsign"] as? String ?? "" print("乘坐 \(lineName) 路,方向:\(headsign)") } } } } // 绘制公交路线到地图 if let polylineDict = firstRoute["overview_polyline"] as? [String: Any], let polylineStr = polylineDict["points"] as? String { let routePath = GMSPath(fromEncodedPath: polylineStr) let routePolyline = GMSPolyline(path: routePath) routePolyline.strokeColor = .systemGreen routePolyline.strokeWidth = 3.0 routePolyline.map = self.mapView } } } catch { print("JSON解析失败:\(error.localizedDescription)") } }.resume() }
实时公交信息
如果需要获取公交实时到站时间等动态信息,需要启用Google Real-Time Transit API,调用方式类似,只需调整API请求的端点和参数,就能获取车辆位置、预计到站时间等数据。
重要注意事项
- 所有API调用都需要有效的Google API密钥,并且要在Google Cloud Console中启用对应的API(Maps SDK for iOS、Directions API、Real-Time Transit API等)。
- 注意API的配额限制和计费规则,避免超出免费额度。
- 实际项目中推荐用
Codable协议做类型安全的JSON解析,上面的示例用JSONSerialization是为了快速展示核心逻辑。
内容的提问来源于stack exchange,提问作者maral
相关产品推荐
相关产品推荐

