我试图在this教程的帮助下显示两个位置之间的路线。他们使用了坐标的CSV文件,我使用谷歌api来获取坐标。但结果完全不同。
你可以看到它没有绘制正确的路径。 Plz向我提出了一些建议。
答案 0 :(得分:14)
您需要解码从响应中获得的折线..为了您需要谷歌的算法......
// http://code.google.com/apis/maps/documentation/utilities/polylinealgorithm.html
//
-(NSMutableArray *)decodePolyLine:(NSString *)encodedStr {
NSMutableString *encoded = [[NSMutableString alloc] initWithCapacity:[encodedStr length]];
[encoded appendString:encodedStr];
[encoded replaceOccurrencesOfString:@"\\\\" withString:@"\\"
options:NSLiteralSearch
range:NSMakeRange(0, [encoded length])];
NSInteger len = [encoded length];
NSInteger index = 0;
NSMutableArray *array = [[[NSMutableArray alloc] init] autorelease];
NSInteger lat=0;
NSInteger lng=0;
while (index < len) {
NSInteger b;
NSInteger shift = 0;
NSInteger result = 0;
do {
b = [encoded characterAtIndex:index++] - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
NSInteger dlat = ((result & 1) ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = [encoded characterAtIndex:index++] - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
NSInteger dlng = ((result & 1) ? ~(result >> 1) : (result >> 1));
lng += dlng;
NSNumber *latitude = [[[NSNumber alloc] initWithFloat:lat * 1e-5] autorelease];
NSNumber *longitude = [[[NSNumber alloc] initWithFloat:lng * 1e-5] autorelease];
// printf("[%f,", [latitude doubleValue]);
// printf("%f]", [longitude doubleValue]);
CLLocation *loc = [[[CLLocation alloc] initWithLatitude:[latitude floatValue] longitude:[longitude floatValue]] autorelease];
[array addObject:loc];
}
[encoded release];
return array;
}
这将为您提供包含所有点的可变数组(以CLLocation对象的形式) 并且也不要只解码主折线..解码你收到的每一个子折线,否则说明方向不合适。
答案 1 :(得分:0)
您可以在代码中添加此简单方法来添加实线(路径):
-(void)addSolidLine:(CLLocation *)source andDestination:(CLLocation*)destination
{
CLLocationCoordinate2D coordinates[2] = {source.coordinate, destination.coordinate};
MKGeodesicPolyline *geodesicPolylineSolid = [MKGeodesicPolyline polylineWithCoordinates:coordinates count:2];
[self.mapView addOverlay:geodesicPolylineSolid];
}
#pragma mark - map view delegate
- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id <MKOverlay>)overlay
{
if ([overlay isKindOfClass:[MKPolyline class]]) {
MKPolylineRenderer *renderer = [[MKPolylineRenderer alloc] initWithPolyline:(MKPolyline *)overlay];
renderer.lineWidth = 1.5f;
renderer.strokeColor = [UIColor greenColor];
renderer.alpha = 50;
return renderer;
}
}
如果你想显示虚线,你可以添加这个方法:
MKPolylineRenderer *renderer = [[MKPolylineRenderer alloc] initWithPolyline:(MKPolyline *)overlay];
renderer.lineDashPattern = @[@2, @5];
renderer.lineWidth = 1.5f;
renderer.strokeColor = [UIColor redColor];
renderer.alpha = 50;
isShowingDottedLine = false;
return renderer;