Google Maps SDK for iOS提供了显示实时交通数据的功能,允许开发者在应用中集成交通流量信息。实时交通数据显示了道路的拥堵情况,通常用颜色编码表示:绿色表示畅通,黄色表示中等拥堵,红色表示严重拥堵。
首先需要在项目中集成Google Maps SDK:
// 在Podfile中添加
pod 'GoogleMaps'
然后运行pod install
。
import UIKit
import GoogleMaps
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// 创建地图视图
let camera = GMSCameraPosition.camera(withLatitude: 37.7749, longitude: -122.4194, zoom: 12)
let mapView = GMSMapView.map(withFrame: view.bounds, camera: camera)
view.addSubview(mapView)
// 启用交通层
mapView.isTrafficEnabled = true
}
}
要显示特定路线的交通数据,需要先绘制路线,然后启用交通层:
func drawRouteAndShowTraffic(from: CLLocationCoordinate2D, to: CLLocationCoordinate2D) {
let origin = "\(from.latitude),\(from.longitude)"
let destination = "\(to.latitude),\(to.longitude)"
let urlString = "https://maps.googleapis.com/maps/api/directions/json?origin=\(origin)&destination=\(destination)&key=YOUR_API_KEY"
guard let url = URL(string: urlString) else { return }
URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data else { return }
do {
let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
guard let routes = json?["routes"] as? [[String: Any]],
let route = routes.first,
let overviewPolyline = route["overview_polyline"] as? [String: Any],
let points = overviewPolyline["points"] as? String else { return }
DispatchQueue.main.async {
let path = GMSPath(fromEncodedPath: points)
let polyline = GMSPolyline(path: path)
polyline.strokeWidth = 4.0
polyline.strokeColor = .blue
polyline.map = self.mapView
// 启用交通层
self.mapView.isTrafficEnabled = true
// 调整相机位置以显示整个路线
if let bounds = self.getBounds(for: path) {
let update = GMSCameraUpdate.fit(bounds, withPadding: 50)
self.mapView.moveCamera(update)
}
}
} catch {
print("Error parsing directions: \(error)")
}
}.resume()
}
func getBounds(for path: GMSPath?) -> GMSCoordinateBounds? {
guard let path = path, path.count() > 0 else { return nil }
var bounds = GMSCoordinateBounds()
for i in 0..<path.count() {
bounds = bounds.includingCoordinate(path.coordinate(at: i))
}
return bounds
}
isTrafficEnabled
是否设置为true