Ios 如何在mapKit中获取管线长度

Ios 如何在mapKit中获取管线长度,ios,mapkit,core-location,Ios,Mapkit,Core Location,我正在使用mapKit绘制一条从一点到另一点的路线。我做到了。 但是我想得到路线长度,而不是直线的距离 nextView.startPoint = [NSString stringWithFormat:@"%f,%f", userLatitude , userLongitude]; nextView.endPoint = [NSString stringWithFormat:@"%f,%f", 30.793636, 31.009641]; [diretions loadWithStartPoin

我正在使用mapKit绘制一条从一点到另一点的路线。我做到了。 但是我想得到路线长度,而不是直线的距离

nextView.startPoint = [NSString stringWithFormat:@"%f,%f", userLatitude , userLongitude];
nextView.endPoint = [NSString stringWithFormat:@"%f,%f", 30.793636, 31.009641];
[diretions loadWithStartPoint:startPoint endPoint:endPoint options:options];

所以我想给它一个路径通过的中点。

要做到这一点,最好使用directions API。你应该看看这个链接并通读一遍,苹果没有内置的DirectionAPI。您可以向它发送请求并请求JSON响应,我将使用and。然后发送请求并解析JSON响应。在响应中,您需要编码的点,这是一组基本上跟踪路线的多个坐标。然后您需要在覆盖图上显示它。以下是一些示例代码,但在复制和粘贴此代码之前,请确保阅读了GDirections API站点,您将更容易理解所有内容,并可以了解如何执行更多操作:

// DRAG IN AFNETWORKING FILES AND JSON KIT FILES TO YOUR PROJECT AND ALSO IMPORT THE MAP KIT AND CORE LOCATION FRAMEWORKS

// IMPORT FILES

#import "StringHelper.h"
#import "JSONKit.h"
#import "AFJSONRequestOperation.h"
#import "AFHTTPClient.h"
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>

// DECLARE MUTABLE ARRAY IN .H:

NSMutableArray *_path;

// ADD THIS CODE TO WHEN YOU WANT TO REQUEST FOR DIRECTIONS

    AFHTTPClient *_httpClient = [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:@"http://maps.googleapis.com/"]];

    [_httpClient registerHTTPOperationClass: [AFJSONRequestOperation class]];

    [_httpClient setDefaultHeader:@"Accept" value:@"application/json"];

    NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];

    [parameters setObject:[NSString stringWithFormat:@"%f,%f", location.coordinate.latitude, location.coordinate.longitude] forKey:@"origin"];

    [parameters setObject:[NSString stringWithFormat:@"%f,%f", location2.coordinate.latitude, location2.coordinate.longitude] forKey:@"destination"];

    [parameters setObject:@"false" forKey:@"sensor"];

    [parameters setObject:@"driving" forKey:@"mode"];

    [parameters setObject:@"metric" forKey: @"units"];

    NSMutableURLRequest *request = [_httpClient requestWithMethod:@"GET" path: @"maps/api/directions/json" parameters:parameters];

    request.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;

    AFHTTPRequestOperation *operation = [_httpClient HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {

        NSInteger statusCode = operation.response.statusCode;

        if (statusCode == 200) {

            [self parseResponse:responseObject];

        }

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) { }];

    [_httpClient enqueueHTTPRequestOperation:operation];

    // NOW ADD THE PARSERESPONSE METHOD
- (void)parseResponse:(NSDictionary *)response {

NSString *status = [response objectForKey: @"status"];

NSArray *routes = [response objectForKey:@"routes"];

NSDictionary *routePath = [routes lastObject];

if (routePath) {

    NSString *overviewPolyline = [[routePath objectForKey: @"overview_polyline"] objectForKey:@"points"];

    _path = [self decodePolyLine:overviewPolyline];

    NSInteger numberOfSteps = _path.count;

    CLLocationCoordinate2D coordinates[numberOfSteps];
    for (NSInteger index = 0; index < numberOfSteps; index++) {
        CLLocation *location = [_path objectAtIndex:index];
        CLLocationCoordinate2D coordinate = location.coordinate;

        coordinates[index] = coordinate;
    }

    polyLine = [MKPolyline polylineWithCoordinates:coordinates count:numberOfSteps];
    [self.mapView addOverlay:polyLine];
}

}

// IMPLEMENTING THE DECODEPOLYLINE METHOD:

-(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];
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];
    NSNumber *longitude = [[NSNumber alloc] initWithFloat:lng * 1e-5];

    CLLocation *location = [[CLLocation alloc] initWithLatitude:[latitude floatValue] longitude:[longitude floatValue]];
    [array addObject:location];
}

return array;

}


// IMPLEMENTING THE VIEWFOROVERLAY DELEGATE METHOD (MAKE SURE TO SET YOUR MAP VIEW'S DELEGATE TO SELF OR THIS WONT GET CALLED) 

- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay {

MKPolylineView *polylineView = [[MKPolylineView alloc] initWithPolyline:overlay];

polylineView.strokeColor = [UIColor blueColor];
polylineView.lineWidth = 5.0;
polylineView.alpha = 0.7;

return polylineView;

}
//将AFNETWORKING文件和JSON工具包文件拖到项目中,并导入地图工具包和核心位置框架
//导入文件
#导入“StringHelper.h”
#导入“JSONKit.h”
#导入“AFJSONRequestOperation.h”
#导入“AFHTTPClient.h”
#进口
#进口
//在.H中声明可变数组:
NSMutableArray*_路径;
//当您要请求指示时,将此代码添加到
AFHTTPClient*\u httpClient=[AFHTTPClient客户端WithBaseURL:[NSURL URLWithString:@]http://maps.googleapis.com/"]];
[_HttpClientRegisterHttPoperationClass:[AFJSONRequestOperation类]];
[_HttpClientSetDefaultHeader:@“接受”值:@“应用程序/json”];
NSMutableDictionary*参数=[[NSMutableDictionary alloc]init];
[parameters setObject:[NSString stringWithFormat:@“%f,%f”,location.coordinate.latitude,location.coordinate.longitude]forKey:@“origin”];
[parameters setObject:[NSString stringWithFormat:@“%f,%f”,location2.coordinate.latitude,location2.coordinate.longitude]forKey:@“destination”];
[parameters setObject:@“false”forKey:@“sensor”];
[parameters setObject:@“driving”forKey:@“mode”];
[parameters setObject:@“metric”forKey:@“units”];
NSMutableURLRequest*request=[\u httpClient requestWithMethod:@“GET”路径:@“maps/api/directions/json”参数:参数];
request.cachePolicy=NSURLRequestReloadIgnoringLocalCacheData;
AFHTTPRequestOperation*操作=[\u httpClient HTTPRequestOperationWithRequest:请求成功:^(AFHTTPRequestOperation*操作,id响应对象){
NSInteger statusCode=operation.response.statusCode;
如果(状态代码==200){
[自我应答:应答对象];
}
}失败:^(AFHTTPRequestOperation*操作,NSError*错误){};
[\u httpClient排队HttpRequestOperation:operation];
//现在添加PARSERESPONSE方法
-(void)parseResponse:(NSDictionary*)响应{
NSString*状态=[response objectForKey:@“状态”];
NSArray*routes=[response objectForKey:@“routes”];
NSDictionary*routePath=[routes lastObject];
如果(路由路径){
NSString*概览多段线=[[routePath objectForKey:@“概览”\u polyline]objectForKey:@“点”];
_路径=[自解码多段线:概览多段线];
NSInteger numberOfSteps=\u path.count;
CLLocationCoordinate2D坐标[步数];
对于(NSInteger index=0;index>1):(结果>>1));
lat+=dlat;
移位=0;
结果=0;
做{
b=[编码字符索引:索引++]-63;
结果|=(b&0x1f)=0x20);
NSInteger dlng=((结果&1)~(结果>>1):(结果>>1));
液化天然气+=液化天然气;
NSNumber*纬度=[[NSNumber alloc]initWithFloat:lat*1e-5];
NSNumber*经度=[[NSNumber alloc]initWithFloat:lng*1e-5];
CLLocation*location=[[CLLocation alloc]initWithLatitude:[纬度浮点值]经度:[经度浮点值]];
[数组addObject:位置];
}
返回数组;
}
//实现VIEWFOROVERLAY委托方法(确保将地图视图的委托设置为SELF,否则将不会调用该委托)
-(MKOverlayView*)地图视图:(MKMapView*)地图视图覆盖:(id)覆盖{
MKPolylineView*polylineView=[[MKPolylineView alloc]initWithPolyline:overlay];
polylineView.strokeColor=[UIColor blueColor];
polylineView.lineWidth=5.0;
polylineView.alpha=0.7;
返回多段线视图;
}

这应该可以让你的定向路由启动并运行起来!

要做到这一点,你最好使用一个定向API。你应该查看这个链接并通读一遍,苹果没有内置的定向API。你可以向它发送一个请求并请求JSON响应,我会使用And。然后发送一个请求并解析它e JSON响应。在响应中,您需要编码的点,这是一组基本上跟踪路线的多个坐标。然后您需要在覆盖图上显示这些点。下面是一些示例代码,但在复制和粘贴之前,请确保您阅读了GDirections