2012-09-02 2 views
0

나는 mapKit을 사용하여 지점 간 경로를 그립니다. 나는 그것을했다. 하지만 나는 거리 길이를 직선으로하고 싶지 않습니다.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]; 

Aloso 경로의 중간 지점을 지정하고 싶습니다.

답변

3

길 찾기 API를 사용해야하므로, 바람직하게는 Google Directions API입니다. 당신은 그 링크를보고 그것을 통해 읽어야합니다, 애플은 방향 API를 내장하고 있지 않습니다. 요청을 보내 JSON 응답을 요청하면 AFNetworking to make like easier (on Github)JSONKit also on Github을 사용합니다. 그런 다음 요청을 보내 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; 

} 

을 그리고 당신의 방향을 얻어야한다 루트가 실행 중!

+0

당신의 협력에 감사합니다 –

+0

만약 당신이 upvote 또는 틱 수 있습니다. – MCKapur

+0

투표를 15 명성이 필요하고 스택에 새로운 .. 죄송합니다 –

관련 문제