我正在尝试使用MKMapView在地图上绘制预先确定的坐标。以下代码由按钮触发。
数组'coordinatesArr'是2D,包含纬度,经度和时间戳。由于其他原因,每个元素都存储为字符串,因此坐标在加载时会转换为双打。
示例:
[["37.33027293", "-122.02788965", "2018-05-30 15:18:21.459808+0100"], ["37.33026014", "-122.02768476", "2018-05-30 15:18:22.459808+0100"]]
代码保存在以下类中:
class PostCell: UITableViewCell, MKMapViewDelegate
代码
(MAP IS THE FOLLOWING OUTLET: @IBOutlet weak var activityFeedMap: MKMapView!)
let span = MKCoordinateSpanMake(0.001, 0.001)
// ALTHOUGH THIS WILL NOT BE MY ULTIMATE METHOD, THE MAP IS CURRENTLY CENTRED ON THE FIRST LOCATION
let myLocation = CLLocationCoordinate2DMake(Double(coordinatesArr[0][1]) ?? 0.0, Double(coordinatesArr[0][0])!)
let region = MKCoordinateRegionMake(myLocation, span)
activityFeedMap.setRegion(region, animated:true)
activityFeedMap.delegate=self
activityFeedMap.mapType = MKMapType.hybrid
// CODE IN QUESTION
// ---
// PERHAPS I SHOULD LOOP THROUGH THE ARRAY, BUT I BELIEVE THIS
// FULFILS THE SAME PURPOSE
var counter=0
while counter < (coordinatesArr.count - 1){
// LASTLOCFORMATTED, AND NEXTLOCFORMATTED ARE EACH A SET OF
// CO-ORDINATES BETWEEN WHICH A POLYLINE SHOULD BE PLOTTED
let lastLocFormatted = CLLocationCoordinate2DMake(Double(coordinatesArr[counter][1])!, Double(coordinatesArr[counter][0])!)
let nextLocFormatted = CLLocationCoordinate2DMake(Double(coordinatesArr[counter+1][1])!, Double(coordinatesArr[counter+1][0])!)
// AN ARRAY HOLDING THE CO-ORDINATES OF THE POINTS TO PLOT
// A POLYLINE BETWEEN
var a=[lastLocFormatted, nextLocFormatted]
// LINE TO PLOT
let polyline = MKPolyline(coordinates: &a, count: counter)
activityFeedMap.add(polyline)
COUNTER += 1
}
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
// CHECK TO SEE WHETHER OVERLAY IS OF TYPE MKPOLYLINE
// AND ONLY LAY TRACE IF TIMER RUNNING
// note: different renderer required for differnt types
if overlay is MKPolyline{
// CREATE MKPOLYLINERENDERER AND PASS OUR OVERLAY OVER
let polylineRenderer = MKPolylineRenderer(overlay: overlay)
// SET LINE COLOR TO BLUE
polylineRenderer.strokeColor = UIColor.orange
// SET LINE WIDTH TO 4
polylineRenderer.lineWidth = 4
return polylineRenderer
}
// IF OVERLAY NOT OF TYPE MKPOLYLINE
return MKPolylineRenderer()
}
虽然这段代码部分有效,但我正以某种方式获得额外的数据。
37.33027293, -122.02788965
37.33026634, -122.0278357
37.33026525, -122.02778504
37.33026222, -122.02773507
37.33026014, -122.02768476
上面应该绘制:
此代码创建以下内容,但
以蓝色标出的线条似乎会无限期地继续下去。
我非常感谢您提供的任何帮助,因为我是Swift的新手并且已经用尽所有我能想到的纠正措施。
谢谢!
答案 0 :(得分:1)
首先,我建议改用https://developer.apple.com/documentation/mapkit/mkpolyline/1452773-polylinewithpoints poloylineWithPoints 为每一个添加折线。
看起来是你的超调,你的最后一段是缩小到零岛。