Created
November 2, 2012 09:09
-
-
Save mmdumi/3999640 to your computer and use it in GitHub Desktop.
Encode polyline. Google Maps API v3 algorithm. Objective c.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
+ (NSString *)encodeStringWithCoordinates:(NSArray *)coordinates | |
{ | |
NSMutableString *encodedString = [NSMutableString string]; | |
int val = 0; | |
int value = 0; | |
CLLocationCoordinate2D prevCoordinate = CLLocationCoordinate2DMake(0, 0); | |
for (NSValue *coordinateValue in coordinates) { | |
CLLocationCoordinate2D coordinate = [coordinateValue MKCoordinateValue]; | |
// Encode latitude | |
val = round((coordinate.latitude - prevCoordinate.latitude) * 1e5); | |
val = (val < 0) ? ~(val<<1) : (val <<1); | |
while (val >= 0x20) { | |
int value = (0x20|(val & 31)) + 63; | |
[encodedString appendFormat:@"%c", value]; | |
val >>= 5; | |
} | |
[encodedString appendFormat:@"%c", val + 63]; | |
// Encode longitude | |
val = round((coordinate.longitude - prevCoordinate.longitude) * 1e5); | |
val = (val < 0) ? ~(val<<1) : (val <<1); | |
while (val >= 0x20) { | |
value = (0x20|(val & 31)) + 63; | |
[encodedString appendFormat:@"%c", value]; | |
val >>= 5; | |
} | |
[encodedString appendFormat:@"%c", val + 63]; | |
prevCoordinate = coordinate; | |
} | |
return encodedString; | |
} | |
// You call it with | |
[... encodeStringWithCoordinates:@[ | |
[NSValue valueWithMKCoordinate:CLLocationCoordinate2DMake(38.5, -120.2)], | |
[NSValue valueWithMKCoordinate:CLLocationCoordinate2DMake(40.7, -120.95)], | |
[NSValue valueWithMKCoordinate:CLLocationCoordinate2DMake(43.252, -126.453)] | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment