我正在尝试在ios7中的谷歌地图上绘制路径。为此,我使用谷歌地图提供的json数据。
NSError *错误;
NSData *jsonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://maps.googleapis.com/maps/api/directions/json?origin=chennai&destination=porur&sensor=false"]];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
//NSLog(@"the json data is %@",jsonDict);
//-- json path --
NSString *polyString = [[[[ jsonDict objectForKey:@"routes"] objectAtIndex:0] objectForKey:@"overview_polyline"] objectForKey:@"points"];
NSString *TotalEstimatedTime = [[[[[[jsonDict objectForKey:@"routes"]objectAtIndex:0] objectForKey:@"legs"] objectAtIndex:0] objectForKey:@"duration"] objectForKey:@"text"];
NSLog(@" %@ ", polyString);
NSLog(@" %@ ", TotalEstimatedTime);
//===================== drawing path ===============================
NSMutableArray *decodepolyString = [self decodePolyLine:polyString];
GMSMutablePath *path = [GMSMutablePath path];
for (int i= 0; i< [decodepolyString count]; i++)
{
CLLocation *location = [decodepolyString objectAtIndex:i];
CLLocationCoordinate2D coordinate = location.coordinate;
[path addCoordinate:coordinate];
}
GMSPolyline *overviewpolyline = [GMSPolyline polylineWithPath:path];
overviewpolyline.strokeColor = [UIColor blueColor];
overviewpolyline.strokeWidth = 4.f;
overviewpolyline.geodesic = YES;
overviewpolyline.map = self.GMSMapView1;
}
- (NSMutableArray *)decodePolyLine:(NSString *)encodedStr { NSMutableString * encoded = [[NSMutableString alloc] initWithCapacity:[encodedStr length]];
[encoded appendString:encodedStr];
[encoded replaceOccurrencesOfString:@"\\\\" withString:@"\\"
options:NSLiteralSearch
range:NSMakeRange(0, [encoded length])];
float len = [encoded length];
float index = 0;
NSMutableArray *array = [[NSMutableArray alloc] init];
float lat=0;
float 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];
NSNumber *longitude = [[NSNumber alloc] initWithFloat:lng * 1e-5];
CLLocation *location = [[CLLocation alloc] initWithLatitude:[latitude floatValue] longitude:[longitude floatValue]];
[array addObject:location];
}
return array;
}