2012-10-22 2 views
5

MapKit에서 두 위치 간의 경로를 그리는 간단한 응용 프로그램을 작성했습니다. Google Map API를 사용하고 있습니다. 온라인에서 찾은 자료를 사용했으며 Google에 요청할 때 사용하는 코드는 다음과 같습니다.MapKit - 맵 확대시 도로를 따라가는 경로를 만듭니다.

_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", coordinate.latitude, coordinate.longitude] forKey:@"origin"]; 
    [parameters setObject:[NSString stringWithFormat:@"%f,%f", endCoordinate.latitude, endCoordinate.longitude] forKey:@"destination"]; 
    [parameters setObject:@"true" forKey:@"sensor"]; 

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

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];  
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject){ 
     NSInteger statusCode = operation.response.statusCode; 

     if (statusCode == 200) 
     { 
      NSLog(@"Success: %@", operation.responseString); 
     } 
     else 
     { 
      NSLog(@"Status code = %d", statusCode); 
     } 
    } 
             failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
              NSLog(@"Error: %@", operation.responseString); 

             } 
    ]; 

    [_httpClient enqueueHTTPRequestOperation:operation]; 

이것은 완벽하게 작동합니다.

LA - Chicago route zoomed out

하지만 : 나는 이것을 실행하고 LA와 시카고 사이의 경로를 표시하려고 할 때 그것이 어떻게 보이는지, 여기. 나는 거리 수준에지도를 확대하면, 여기에 경로가 보이는 방법은 다음과 같습니다

LA - Chicago route zoomed in

사람이지도를 확대하면 내가 그리기하고 그 경로가 거리를 다음과 달성 할 수있는 방법을 알고 있나요? 거리를 통해 정확한 경로를 표시하는 경로를 원합니다. 일부 추가 매개 변수를 Google에 대한 요청에 추가해야하는지 여부는 알 수 없습니다.

도움이나 조언이 도움이 될 것입니다. 미리 많은 감사드립니다!


[편집 # 1 : 구글에서 요청 URL 및 응답 추가]

위의 코드에서 작업 객체를 생성 한 후 내 요청 URL은 다음과 같습니다를 :

http://maps.googleapis.com/maps/api/directions/json?sensor=true&destination=34%2E052360,-118%2E243560&origin=41%2E903630,-87%2E629790 

그냥 붙여 넣기 브라우저 URL을 입력하면 JSON 데이터가 Google 코드로 전송되는 응답으로 전송됩니다.


: 나는 MapKit에서 사용하는 투사 Google지도에서 사용하는 것과 다른 것을 생각

- (void)parseResponse:(NSData *)response 
{ 
    NSDictionary *dictResponse = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableContainers error:nil]; 
    NSArray *routes = [dictResponse objectForKey:@"routes"]; 
    NSDictionary *route = [routes lastObject]; 

    if (route) 
    { 
     NSString *overviewPolyline = [[route objectForKey: @"overview_polyline"] objectForKey:@"points"]; 
     _path = [self decodePolyLine:overviewPolyline]; 
    } 
} 

- (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; 
} 
+0

이 라이브러리를 사용하고 있습니다. 이것은 나를 위해 잘 작동하고 있습니다. https://github.com/kadirpekel/MapWithRoutes –

답변

1

것 같습니다. 실제로, 나는 여러분과 같은 장소 표시뿐만 아니라 (직선과 함께) 보이는 아이콘 사이의 폴리선을 기대합니다. 당신이

  • 구글이 다시 보내는 JSON 데이터를 제공 제한하는 경우 응답

    • 확인으로 DirectionsStatus 확인합니다.

    Google에서 사용하는 완전히 다른 Mercator 투영법을 사용하고 있는지 잘 모르겠습니다.

    +0

    답변 해 주셔서 감사합니다, Cyril. 내 질문에 편집 # 1을 확인하고 거기에 요청한 데이터를 제공했습니다. – uerceg

    +0

    편집 # 2에서 Google의 응답을 구문 분석하고 경로를 빌드하는 소스 코드를 추가했습니다. 지금은 DRIVING에서 WALKING으로 모드를 변경하려고했는데 재미있는 점은 Google의 JSON 응답이 DRIVING 모드보다 분명히 크다는 것입니다. 아직 끝나기 205 도로에서 경로를 찾았고 DRIVING에서 203 좌표를 얻습니다. 통로. 이상한. – uerceg

    +0

    불행히도 길 찾기 API에 대한 지식이 부족하여 도움이되지 않습니다. "overview_polyline은 결과 방향의 근사 (평탄화 된) 경로를 나타내는 인코딩 된 점의 배열을 보유하는 객체를 포함합니다."문서의 핵심 요소는 핵심 요소라고 생각합니다. 짧은 경로로 같은 요청을 시도하고 더 정확하거나 더 나은 방법인지 확인해보십시오. NY 또는 LA와 같이 실제로 정사각형 인 경로를 시도하여 가까운 경로를 요청할 때 경로가 개선되는지 확인하십시오. –

    0

    [편집 # 2 구글에서 답을 구문 분석하고 경로를 구축]. MapKit uses Cylindrical Mercator, Google uses a variant of the Mercator Projection. 당신이 다른 좌표계에서 변환해야 할 때 일반적으로, 있을 수 있습니다 위도와 경도 값을 사용하여지도에 점을 지정할 수 있지만 시스템 좌표 사이의 변환

    . 예를 들어, 오버레이 모양을 지정할 때 일반적으로 맵 포인트를 사용합니다. Apple에서 인용

    : Google은 당신에게 모든 포인트를 제공하지 않거나 당신이 모든 점을보고하지 않는 것처럼

    관련 문제