Как создать линию (полилинию) между точками расположения в Swift?
Я пытаюсь создать приложение, которое отслеживает местоположение пользователя и создает строку, следующую за тем, куда ушел пользователь. Я создал кучу аннотаций после того, как пользователь пошел, но не могу понять, как создать линию между ними. Я новичок в Swift и XCode, и я просмотрел весь интернет, но не могу найти ничего, что работает. Изображение приложения с аннотациями после местоположения пользователя
Вот мой код:
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet var mapView: MKMapView?
//Map
@IBOutlet weak var map: MKMapView!
@IBOutlet weak var lblSpeed: UILabel!
let manager = CLLocationManager()
@IBOutlet weak var lblAltitude: UILabel!
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations[0]
let span:MKCoordinateSpan = MKCoordinateSpanMake(0.01, 0.01)
let myLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)
let region:MKCoordinateRegion = MKCoordinateRegionMake(myLocation, span)
lblAltitude.text = String(format:"%.2f", location.altitude)
lblSpeed.text = String(format:"%.2f", location.speed)
self.map.showsUserLocation = true
var testLocation = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)
var annotation = MKPointAnnotation()
annotation.coordinate = testLocation
map.addAnnotation(annotation)
var locationTest = [CLLocation(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)]
var coordinates = locations.map({(location: CLLocation!) -> CLLocationCoordinate2D in return location.coordinate})
var polyline = MKPolyline(coordinates: &testLocation, count: locations.count)
func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! {
if overlay is MKPolyline {
let polylineRenderer = MKPolylineRenderer(overlay: overlay)
polylineRenderer.strokeColor = UIColor.blue
polylineRenderer.lineWidth = 5
return polylineRenderer
}
return nil
}
}
1 ответ
Ты можешь попробовать
let blueLocation1 = CLLocationCoordinate2D(latitude: lat1, longitude: lon1)
let blueLocation2 = CLLocationCoordinate2D(latitude: lat2, longitude: lon2)
let routeLine = MKPolyline(coordinates:[blueLocation1,blueLocation2], count:2)
self.mapView.add(routeLine)
// Также вам может понадобиться уменьшить масштаб, чтобы показать все аннотации + видя нарисованную линию
func zoomToFitMapAnnotations(aMapView:MKMapView)
{
if(aMapView.annotations.count == 0)
{
return
}
var topLeftCoord = CLLocationCoordinate2D.init(latitude: -90, longitude: 180)
var bottomRightCoord = CLLocationCoordinate2D.init(latitude: 90, longitude: -180)
for i in 0..<aMapView.annotations.count
{
let annotation = aMapView.annotations[i]
topLeftCoord.longitude = fmin(topLeftCoord.longitude, annotation.coordinate.longitude);
topLeftCoord.latitude = fmax(topLeftCoord.latitude, annotation.coordinate.latitude);
bottomRightCoord.longitude = fmax(bottomRightCoord.longitude, annotation.coordinate.longitude);
bottomRightCoord.latitude = fmin(bottomRightCoord.latitude, annotation.coordinate.latitude);
}
let resd = CLLocationCoordinate2D.init(latitude: topLeftCoord.latitude - (topLeftCoord.latitude - bottomRightCoord.latitude) * 0.5, longitude: topLeftCoord.longitude + (bottomRightCoord.longitude - topLeftCoord.longitude) * 0.5)
let span = MKCoordinateSpan.init(latitudeDelta: fabs(topLeftCoord.latitude - bottomRightCoord.latitude) * 1.3, longitudeDelta: fabs(bottomRightCoord.longitude - topLeftCoord.longitude) * 1.3)
var region = MKCoordinateRegion.init(center: resd, span: span);
region = aMapView.regionThatFits(region)
aMapView.setRegion(region, animated: true)
}
// Также rendererForOverlay
func должен быть на уровне класса, а не внутри другого func
func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! {
if overlay is MKPolyline {
let polylineRenderer = MKPolylineRenderer(overlay: overlay)
polylineRenderer.strokeColor = UIColor.blue
polylineRenderer.lineWidth = 5
return polylineRenderer
}
return nil
}