當我必須在我們的一個應用程序中實現turn-by-turn時,我使用了你描述的第一個項目符號。爲了弄清楚用戶是否偏離了原始多段線,我每次讀新位置時都會計算出當前位置和線段之間的距離。一旦我檢測到我沒有遵循路徑,我重新計算路線,同時顯示用戶的「重新計算...」消息。
這是我的代碼
- (BOOL)isCoordinate:(CLLocationCoordinate2D)coordinate closeToPolyline:(MKPolyline *)polyline {
CLLocationCoordinate2D polylineCoordinates[polyline.pointCount];
[polyline getCoordinates:polylineCoordinates range:NSMakeRange(0, polyline.pointCount)];
for (int i = 0; i < polyline.pointCount - 1; i++) {
CLLocationCoordinate2D a = polylineCoordinates[i];
CLLocationCoordinate2D b = polylineCoordinates[i + 1];
double distance = [self distanceToPoint:MKMapPointForCoordinate(coordinate) fromLineSegmentBetween:MKMapPointForCoordinate(a) and:MKMapPointForCoordinate(b)];
if (distance < 25) {
return YES;
}
}
return NO;
}
- (double)distanceToPoint:(MKMapPoint)p fromLineSegmentBetween:(MKMapPoint)l1 and:(MKMapPoint)l2 {
double A = p.x - l1.x;
double B = p.y - l1.y;
double C = l2.x - l1.x;
double D = l2.y - l1.y;
double dot = A * C + B * D;
double len_sq = C * C + D * D;
double param = dot/len_sq;
double xx, yy;
if (param < 0 || (l1.x == l2.x && l1.y == l2.y)) {
xx = l1.x;
yy = l1.y;
}
else if (param > 1) {
xx = l2.x;
yy = l2.y;
}
else {
xx = l1.x + param * C;
yy = l1.y + param * D;
}
return MKMetersBetweenMapPoints(p, MKMapPointMake(xx, yy));
}
然後我叫- (BOOL)isCoordinate:(CLLocationCoordinate2D)coordinate closeToPolyline:(MKPolyline *)polyline {
與coordinate
是用戶當前的位置和polyline
從MKDirections
是路徑。
在我的情況下,我不會允許超過25米的距離,但它可能取決於您的緯度/經度精度。
也許它會幫助你或某人。
感謝您的回答。我認爲不清楚的是,我將如何根據距離_沿着路線_(直線)來計算出最近的POI。 – KPM 2014-10-07 16:28:43
@KPM我添加了說明。 – 2014-10-07 16:39:56
謝謝!我也發現這個相關的問答很有用:http://stackoverflow.com/questions/14789706/calculate-distance-of-mkpolyline-path – KPM 2014-10-07 16:45:18