How to decode the Google Directions API polylines field into lat long points in Objective-C for iPhone?

后端 未结 13 1002
孤街浪徒
孤街浪徒 2020-11-30 19:05

I want to draw routes on a map corresponding to directions JSON which I am getting through the Google Directions API: https://developers.google.com/maps/documentation/direct

13条回答
  •  我在风中等你
    2020-11-30 19:36

    For Google maps it already have a straight forward method , polylineWithPath, so I prefer this snippet.

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

提交回复
热议问题