The new version of MapKit in iOS 4 supports polylines, finally. MKPolyline to be precise.
I have been working with the Google Maps API for a while and now I’m learning Objective-C and writing an iPhone app ro Route.ly
Since the best way to send around the net the data to draw a polyline on a map is in encoded format I decided to write a small Objective-C function to decode the encoded string. Since I couldn’t find this anywhere on the net I decided to publish the code here.
You’ll notice that at the beginning of the function I replace “\\\\” with “\\”. This is because I use the encoded data both in web pages with javascript and my iPhone app. In javascript “\\” would be considered an escape and would therefore break my array of points. This is not the case in Objective-C so I switch back to the normal “\\”.
NSString escapedEncodedPoints = [encodedPoints stringByReplacingOccurrencesOfString:@"\\\\" withString:@"\\"];
int len = [escapedEncodedPoints length];
NSMutableArray waypoints = [[NSMutableArray alloc] init];
int index = 0;
float lat = 0;
float lng = 0;
while (index < len) {
char b;
int shift = 0;
int result = 0;
do {
b = [escapedEncodedPoints characterAtIndex:index++] - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0×20);
float dlat = ((result & 1) ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = [escapedEncodedPoints characterAtIndex:index++] - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0×20);
float dlng = ((result & 1) ? ~(result >> 1) : (result >> 1));
lng += dlng;
float finalLat = lat * 1e-5;
float finalLong = lng * 1e-5;
Waypoint *newPoint = [[Waypoint alloc] init];
newPoint.lat = [[NSString alloc] initWithFormat:@"%f", finalLat];
newPoint.lng = [[NSString alloc] initWithFormat:@"%f", finalLong];
[waypoints addObject:newPoint];
[newPoint release];
}
return waypoints;
}
Waypoints is a simple model class I’ve written with two NSString properties: lat and lng.













