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

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


I hope it's not against the rules to link to my own blog post if it's relevant to the question, but I've solved this problem in the past. Stand-alone answer from linked post:

@implementation MKPolyline (MKPolyline_EncodedString)+ (MKPolyline *)polylineWithEncodedString:(NSString *)encodedString {    const char *bytes = [encodedString UTF8String];    NSUInteger length = [encodedString lengthOfBytesUsingEncoding:NSUTF8StringEncoding];    NSUInteger idx = 0;    NSUInteger count = length / 4;    CLLocationCoordinate2D *coords = calloc(count, sizeof(CLLocationCoordinate2D));    NSUInteger coordIdx = 0;    float latitude = 0;    float longitude = 0;    while (idx < length) {        char byte = 0;        int res = 0;        char shift = 0;        do {            byte = bytes[idx++] - 63;            res |= (byte & 0x1F) << shift;            shift += 5;        } while (byte >= 0x20);        float deltaLat = ((res & 1) ? ~(res >> 1) : (res >> 1));        latitude += deltaLat;        shift = 0;        res = 0;        do {            byte = bytes[idx++] - 0x3F;            res |= (byte & 0x1F) << shift;            shift += 5;        } while (byte >= 0x20);        float deltaLon = ((res & 1) ? ~(res >> 1) : (res >> 1));        longitude += deltaLon;        float finalLat = latitude * 1E-5;        float finalLon = longitude * 1E-5;        CLLocationCoordinate2D coord = CLLocationCoordinate2DMake(finalLat, finalLon);        coords[coordIdx++] = coord;        if (coordIdx == count) {            NSUInteger newCount = count + 10;            coords = realloc(coords, newCount * sizeof(CLLocationCoordinate2D));            count = newCount;        }    }    MKPolyline *polyline = [MKPolyline polylineWithCoordinates:coords count:coordIdx];    free(coords);    return polyline;}@end


The best and lightest answer should be to use the method provided by Google in the framework :

[GMSPolyline polylineWithPath:[GMSPath pathFromEncodedPath:encodedPath]]


If you are working with Google Map on iOS and want to draw the route including the polylines, google itself provides an easier way to get the GMSPath from polyline as,

GMSPath *pathFromPolyline = [GMSPath pathFromEncodedPath:polyLinePoints];

Here is the complete code:

+ (void)callGoogleServiceToGetRouteDataFromSource:(CLLocation *)sourceLocation toDestination:(CLLocation *)destinationLocation onMap:(GMSMapView *)mapView_{    NSString *baseUrl = [NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/directions/json?origin=%f,%f&destination=%f,%f&sensor=false", sourceLocation.coordinate.latitude,  sourceLocation.coordinate.longitude, destinationLocation.coordinate.latitude,  destinationLocation.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) {        GMSMutablePath *path = [GMSMutablePath path];        NSError *error = nil;        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];        NSArray *routes = [result objectForKey:@"routes"];        NSDictionary *firstRoute = [routes objectAtIndex:0];        NSDictionary *leg =  [[firstRoute objectForKey:@"legs"] objectAtIndex:0];        NSArray *steps = [leg objectForKey:@"steps"];        int stepIndex = 0;        CLLocationCoordinate2D stepCoordinates[1  + [steps count] + 1];        for (NSDictionary *step in steps) {            NSDictionary *start_location = [step objectForKey:@"start_location"];            stepCoordinates[++stepIndex] = [self coordinateWithLocation:start_location];            [path addCoordinate:[self coordinateWithLocation:start_location]];            NSString *polyLinePoints = [[step objectForKey:@"polyline"] objectForKey:@"points"];            GMSPath *polyLinePath = [GMSPath pathFromEncodedPath:polyLinePoints];            for (int p=0; p<polyLinePath.count; p++) {                [path addCoordinate:[polyLinePath coordinateAtIndex:p]];            }            if ([steps count] == stepIndex){                NSDictionary *end_location = [step objectForKey:@"end_location"];                stepCoordinates[++stepIndex] = [self coordinateWithLocation:end_location];                [path addCoordinate:[self coordinateWithLocation:end_location]];            }        }        GMSPolyline *polyline = nil;        polyline = [GMSPolyline polylineWithPath:path];        polyline.strokeColor = [UIColor grayColor];        polyline.strokeWidth = 3.f;        polyline.map = mapView_;    }];}+ (CLLocationCoordinate2D)coordinateWithLocation:(NSDictionary*)location{    double latitude = [[location objectForKey:@"lat"] doubleValue];    double longitude = [[location objectForKey:@"lng"] doubleValue];    return CLLocationCoordinate2DMake(latitude, longitude);}