我想在MKMapView上使用googleMap Api绘制折线。 我这样做。这是代码。
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager.requestSerializer setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
NSString *urlString =@"https://maps.googleapis.com/maps/api/directions/json";
NSString *origin = @"23.0061,72.5647";
NSString *dstinatin = @"23.03293,72.6284";
MKPointAnnotation *annotationEnd = [[MKPointAnnotation alloc] init];
[annotationEnd setCoordinate:CLLocationCoordinate2DMake(23.0293, 72.6284)];
[annotationEnd setTitle:@"Ending"]; //You can set the subtitle too
[self.mkMapView addAnnotation:annotationEnd];
NSDictionary *dictParameters = @{@"origin" : [NSString stringWithFormat:@"%@",origin], @"destination" : [NSString stringWithFormat:@"%@",dstinatin], @"mode" : @"driving", @"sensor" : @"true"};
[manager GET:urlString parameters:dictParameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSArray *routesArray = [responseObject objectForKey:@"routes"];
if ([routesArray count] > 0)
{
NSDictionary *routeDict = [routesArray objectAtIndex:0];
NSDictionary *routeOverviewPolyline = [routeDict objectForKey:@"overview_polyline"];
NSString *points = [routeOverviewPolyline objectForKey:@"points"];
MKPolyline *line = [self polylineWithEncodedString:points];
[mkMapView addOverlay:line];
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
我的解码方法是:
-(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;
}
我认为我的编码还可以,但我没有得到正确的折线。我正如屏幕截图中看到的那样。折线的最后一端应该在我的MKPointAnnotation上。对不起我的英语不好。请帮帮我。
答案 0 :(得分:3)
路线的目的地:
23.03293,72.6284
//____^
不等于标记位置:
23.0293,72.6284