Virat Naithani Virat Naithani - 6 months ago 65
iOS Question

Drawing Path between two locations using MKPolyline

I am trying to show route between two locations with the help of this tutorial. They have used a CSV file of coordinates and i am using google api to get coordinates. But Result is completely different.
Output

as you can see it is not drawing correct path.
Plz suggest me something.

Answer

You need to the decode the polyline that you are getting from the response.. and in order to that you need google's algorithm...

// http://code.google.com/apis/maps/documentation/utilities/polylinealgorithm.html  
//  
-(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] autorelease];  
    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] autorelease];  
        NSNumber *longitude = [[[NSNumber alloc] initWithFloat:lng * 1e-5] autorelease];  
        //          printf("[%f,", [latitude doubleValue]);  
        //          printf("%f]", [longitude doubleValue]);  
        CLLocation *loc = [[[CLLocation alloc] initWithLatitude:[latitude floatValue] longitude:[longitude floatValue]] autorelease];  
        [array addObject:loc];  
    }  
    [encoded release];  
    return array;  
}

this will give you the mutable array with all the points (in the form of CLLocation objects) and also dont just decode the main polyline .. decode each and every sub polyline that you receive and than plot otherwise the directions will not be proper.