计划是为驾驶员绘制折线。驱动程序的坐标来自API并保存在Place
中。每1分钟在数据库中更新驱动程序的坐标。
我有一个代码,我尝试过工作,但它没有在地图上显示任何内容。
var places = [Place]()
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
requestLocationAccess()
addAnnotations()
addPolyline()
addPolygon()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
getOrderData ()
}
func addAnnotations() {
mapView?.delegate = self
mapView?.addAnnotations(places)
let overlays = places.map { MKCircle(center: $0.coordinate, radius: 20) }
mapView?.addOverlays(overlays)
// Add polylines
var locations = places.map { $0.coordinate }
print("Number of locations: \(locations.count)")
let polyline = MKPolyline(coordinates: &locations, count: locations.count)
mapView?.add(polyline)
}
func addPolyline() {
var locations = places.map { $0.coordinate }
let polyline = MKPolyline(coordinates: &locations, count: locations.count)
mapView?.add(polyline)
}
func addPolygon() {
var locations = places.map { $0.coordinate }
let polygon = MKPolygon(coordinates: &locations, count: locations.count)
mapView?.add(polygon)
}
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
if overlay is MKCircle {
let renderer = MKCircleRenderer(overlay: overlay)
renderer.fillColor = UIColor.black.withAlphaComponent(0.5)
renderer.strokeColor = UIColor.blue
renderer.lineWidth = 2
return renderer
} else if overlay is MKPolyline {
let renderer = MKPolylineRenderer(overlay: overlay)
renderer.strokeColor = UIColor.orange
renderer.lineWidth = 3
return renderer
} else if overlay is MKPolygon {
let renderer = MKPolygonRenderer(polygon: overlay as! MKPolygon)
renderer.fillColor = UIColor.black.withAlphaComponent(0.5)
renderer.strokeColor = UIColor.orange
renderer.lineWidth = 2
return renderer
}
return MKOverlayRenderer()
}
func getOrderData () {
let param = ["user_id":"12299"]
let urlStr = "/client/current_order"
let url = URL(string: urlStr)
Alamofire.request(url!, method: .post, parameters: param,encoding: URLEncoding.default, headers: headers).responseJSON { response in
// get data
let driver = data["orders"][0]["driver"]
let lat = driver["lat"].stringValue
let lng = driver["lng"].stringValue
let position = Place(coordinate: CLLocationCoordinate2DMake(Double(lat)!, Double(lng)!))
self.places.append(position)
print(self.places)
}
结果是一张空地图。