2014-05-13 3 views
0

iOS의 Google지도에서 두 위치 사이에 경로를 만들려고합니다. 다음 코드를 사용하여 두 위치 사이에 경로를 그릴 수 있습니다. 이 코드에서는 Google지도 키와 장소 키를 사용하고 있습니다. 나는 그때가 가까워지면 시간이 올 것이다. 그러나 내가 먼 거리에 그림을 그릴 때, 멀리지도를 따라 가려하지 않는다.Google지도에서 전체 절묘한 폴리 라인을 그릴 수 없습니다. iOS가있는 경우

#import "MPOWGetDirections.h" 

@implementation MPOWGetDirections 

-(void) setSearchModeOption:(MPGetDirectionOption)option 
    { 
     searchModeOption = option; 
     NSLog(@"option setted: %i",option); 
    } 

-(int) requestDirecionsAndshowOnMap:(GMSMapView *)aMapView 
    { 
     NSArray* mode = [[NSArray alloc]initWithObjects:@"transit",@"bicycling",@"walking",@"driving", nil]; 
     NSString *depart = [[NSString alloc] initWithFormat:@""]; 
     NSString *origin = [[NSString alloc] initWithFormat:@""]; 
     NSString *destination = [[NSString alloc] initWithFormat:@""]; 



    //================== set Langauge ========================== 

     if (self.setLanguage) 

      self.setLanguage=[NSString stringWithFormat:@"language=%@",self.setLanguage]; 
     else 
      [email protected]"language=en"; 


    //================== set Search Mode ========================== 

     if (searchModeOption==0) 
      { 
       if (self.departDate==nil) 
       { 
        self.departDate=[NSDate date]; 
       } 

       depart=[NSString stringWithFormat:@"&departure_time=%i",(int)[self.departDate timeIntervalSince1970]]; 
      } 

    //================== set Origian ========================== 

     if (self.origin) 
      { 
       origin = [NSString stringWithFormat:@"origin=%@",self.origin]; 
      } 
     else if (self.originCoordinate.latitude && self.originCoordinate.longitude) 
      { 
       origin = [NSString stringWithFormat:@"origin=%f,%f",self.originCoordinate.latitude,self.originCoordinate.longitude]; 
      } 
     else 
      { 
       NSLog(@"No origin setted"); 
       return -1; 
      } 

    //================== set Destination ========================== 

     if (self.destination) 
      { 
       destination=[NSString stringWithFormat:@"destination=%@",self.destination]; 
      } 
     else if (self.destinationCoordinate.latitude && self.destinationCoordinate.longitude) 
      { 
       destination=[NSString stringWithFormat:@"destination=%f,%f",self.destinationCoordinate.latitude,self.destinationCoordinate.longitude]; 
      } 
     else 
      { 
       NSLog(@"No destination setted"); 
       return -1; 
      } 


    //================== set Full Url and Request ========================== 



    NSString* URLforRequest=[[NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/directions/json?%@&%@&sensor=false&%@&alternative=true&mode=%@%@",origin,destination,self.setLanguage,[mode objectAtIndex:searchModeOption],depart] stringByAddingPercentEscapesUsingEncoding: NSASCIIStringEncoding]; 

     NSLog(@"%@",URLforRequest); 




     NSURLRequest *requests = [NSURLRequest requestWithURL:[NSURL URLWithString:URLforRequest]]; 



     [NSURLConnection sendAsynchronousRequest:requests queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) 
     { 

      if (error==nil && data) 
       { 
        // NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]); 

        directions = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error]; 


        if (error) 
         { 
          NSLog(@"%@",error); 
         } 

        NSString* status=[directions objectForKey:@"status"]; 
        NSLog(@"Status: %@", status); 

        if ([status isEqualToString:@"OK"]) 
         { 
          [self decodeResult]; 

          if (aMapView) 
          [self showOnMap:aMapView]; 
         } 
       } 
      else 
       NSLog(@"%@",error); 


      [[NSNotificationCenter defaultCenter] postNotificationName:@"Request Done" object:nil]; 


     }]; 


    return 0; 
} 

-(void) decodeResult 
    { 

    self.destination=[[[[[directions objectForKey:@"routes"] objectAtIndex:0] objectForKey:@"legs"] objectAtIndex:0] objectForKey:@"end_address"]; 

    self.distance=[[[[[[[directions objectForKey:@"routes"] objectAtIndex:0] objectForKey:@"legs"] objectAtIndex:0] objectForKey:@"distance"] objectForKey:@"text"] doubleValue]; 

    self.duration=[[[[[[directions objectForKey:@"routes"] objectAtIndex:0] objectForKey:@"legs"] objectAtIndex:0] objectForKey:@"duration"] objectForKey:@"text"]; 

    //Get Array of Instructions 

    self.instrunctions=[[NSMutableArray alloc] init]; 

    for (int n=0; n<[[[[[[directions objectForKey:@"routes"] objectAtIndex:0] objectForKey:@"legs"] objectAtIndex:0] objectForKey:@"steps"]count]; n++) { 
     [self.instrunctions addObject:[[[[[[[directions objectForKey:@"routes"] objectAtIndex:0] objectForKey:@"legs"] objectAtIndex:0] objectForKey:@"steps"] objectAtIndex:n] objectForKey:@"html_instructions"]]; 
    } 

    //Get Overview Polyline ==== Path===== 

    NSString *polystring=[[[[directions objectForKey:@"routes"] objectAtIndex:0] objectForKey:@"overview_polyline"] objectForKey:@"points"]; 
    NSMutableArray* decodedpolystring=[self decodePolyLine:polystring]; 

    int numberOfCC=[decodedpolystring count]; 

    GMSMutablePath *path = [GMSMutablePath path]; 

    for (int index = 0; index < numberOfCC; index++) 
     { 
      CLLocation *location = [decodedpolystring objectAtIndex:index]; 
      CLLocationCoordinate2D coordinate = location.coordinate; 
      [path addLatitude:coordinate.latitude longitude:coordinate.longitude]; 
     } 




    self.overviewPolilyne= [GMSPolyline polylineWithPath:path]; 

    //Get Coordinates of origin and destination to be displayed on a map 

    float lat=[[[[[[[directions objectForKey:@"routes"] objectAtIndex:0] objectForKey:@"legs"]objectAtIndex:0] objectForKey:@"end_location"] objectForKey:@"lat"] floatValue]; 

    float lng=[[[[[[[directions objectForKey:@"routes"] objectAtIndex:0] objectForKey:@"legs"]objectAtIndex:0] objectForKey:@"end_location"] objectForKey:@"lng"] floatValue]; 


    CLLocationCoordinate2D tmp; 
    tmp.latitude=lat; 
    tmp.longitude=lng; 
    self.destinationCoordinate=tmp; 


    lat=[[[[[[[directions objectForKey:@"routes"] objectAtIndex:0] objectForKey:@"legs"]objectAtIndex:0] objectForKey:@"start_location"] objectForKey:@"lat"] floatValue]; 
    lng=[[[[[[[directions objectForKey:@"routes"] objectAtIndex:0] objectForKey:@"legs"]objectAtIndex:0] objectForKey:@"start_location"] objectForKey:@"lng"] floatValue]; 


    tmp.latitude=lat; 
    tmp.longitude=lng; 
    self.originCoordinate=tmp; 

} 



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

-(void)showOnMap:(GMSMapView *)aMapView{ 
    GMSPolyline *polyline =self.overviewPolilyne; 
    polyline.strokeColor = [UIColor blueColor]; 
    polyline.strokeWidth = 2.f; 
    polyline.geodesic = YES; 
    polyline.map = aMapView; 


} 

@end 
` 

내가 실수하고있는 것을 알 수 있습니까?

+0

유 어떤 대답 @Mantosh – madLokesh

+0

중복 된 질문을 얻었 는가 : 여기에 질문 http://stackoverflow.com/a/9219856/454165 –

+0

가능한 중복 응답 [위도 긴으로 구글 길 찾기 API 폴리 라인 필드를 디코딩하는 방법 포인트는 객관적으로 - C for iPhone?] (http://stackoverflow.com/questions/9217274/how-to-decode-the-google-directions-api-polylines-field-into-lat-long-points-in) –

답변

1

나는 GOOGLE MAPS를 사용하고 있다면이 방법을 선호합니다.

GMSPolyline *polyPath = [GMSPolyline polylineWithPath:[GMSPath pathFromEncodedPath:encodedPath]]; 

다음은 전체 코드 단편입니다.

-(void)drawPathFrom:(CLLocation*)source toDestination:(CLLocation*)destination{ 

    NSString *baseUrl = [NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/directions/json?origin=%f,%f&destination=%f,%f&sensor=true", source.coordinate.latitude, source.coordinate.longitude, destination.coordinate.latitude, destination.coordinate.longitude]; 

    NSURL *url = [NSURL URLWithString:[baseUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; 
    NSLog(@"Url: %@", url); 
    NSURLRequest *request = [NSURLRequest requestWithURL:url]; 

    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { 
     if(!connectionError){ 
      NSDictionary *result  = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; 
      NSArray *routes    = [result objectForKey:@"routes"]; 
      NSDictionary *firstRoute = [routes objectAtIndex:0]; 
      NSString *encodedPath  = [firstRoute[@"overview_polyline"] objectForKey:@"points"]; 

      GMSPolyline *polyPath  = [GMSPolyline polylineWithPath:[GMSPath pathFromEncodedPath:encodedPath]]; 
      polyPath.strokeColor  = [UIColor redColor]; 
      polyPath.strokeWidth  = 3.5f; 
      polyPath.map    = _mapView; 
     } 
    }]; 

} 
0

두 경로 BTW 두 곳을 그리려면이 방법을 사용하십시오. 그 데모 swift 방법은 두 장소의 패배를 찾을 수 있습니다.

//MARK: API CALL 
func GetRoughtofTwoLocation(){ 
    let originString: String = "\(23.5800),\(72.5853)" 
    let destinationString: String = "\(24.5836),\(72.5853)" 
    let directionsAPI: String = "https://maps.googleapis.com/maps/api/directions/json?" 
    let directionsUrlString: String = "\(directionsAPI)&origin=\(originString)&destination=\(destinationString)&mode=driving" 

    APICall().callApiUsingWithFixURLGET(directionsUrlString, withLoader: true) { (responceData) -> Void in 
     let json = responceData as! NSDictionary 
     let routesArray: [AnyObject] = (json["routes"] as! [AnyObject]) 
     var polyline: GMSPolyline? = nil 
     if routesArray.count > 0 { 
      let routeDict: [NSObject : AnyObject] = routesArray[0] as! [NSObject : AnyObject] 
      var routeOverviewPolyline: [NSObject : AnyObject] = (routeDict["overview_polyline"] as! [NSObject : AnyObject]) 
      let points: String = (routeOverviewPolyline["points"] as! String) 
      let path: GMSPath = GMSPath(fromEncodedPath: points)! 
      polyline = GMSPolyline(path: path) 
      polyline!.strokeWidth = 2.0 
      polyline!.map = self.mapView 
     } 

    } 
}