所以,我在我的应用中使用了Directions API。但是,当我从响应中解码折线时,它没有正确显示。这是我的代码:
//Construct request URL
NSString *urlString = [NSString stringWithFormat:
@"%@?origin=%f,%f&destination=%f,%f&sensor=true&key=%@",
@"https://maps.googleapis.com/maps/api/directions/json",
userMarker.position.latitude,
userMarker.position.longitude,
place.coordinate.latitude,
place.coordinate.longitude,
@"AIzaSyDrtHA-AMiVVylUPcp46_Vf1eZJJFBwRCY"];
NSURL *directionsURL = [NSURL URLWithString:urlString];
//Get directions in JSON format
dispatch_async(dispatch_get_main_queue(), ^{
NSData* data = [NSData dataWithContentsOfURL:directionsURL];
NSError* error;
if(data){
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
//Parse JSON and plot route on map
NSDictionary *routes = [json objectForKey:@"routes"][0];
NSDictionary *route = [routes objectForKey:@"overview_polyline"];
NSString *overview_route = [route objectForKey:@"points"];
//Clear map from previous polylines
[self.mapView clear];
//Make polyline
GMSPath *path = [GMSPath pathFromEncodedPath:overview_route];
GMSPolyline *polyline = [GMSPolyline polylineWithPath:path];
polyline.strokeWidth = 4;
polyline.strokeColor = [UIColor darkGrayColor];
polyline.map = self.mapView;
});
这是折线:
尽可能地看,它没有正确地遵循道路。然而,对我而言似乎没有足够的点来进行适当的弯曲。
编辑:这只发生在50%的时间,有时它会正确显示,有时则不会。
我可能做错了什么?
答案 0 :(得分:0)
通过这个(使用js API而不是你正在使用的json API):
Get a polyline from Google maps directions V3
看起来你应该在响应中使用legs
的每个步骤中的行,而不是overview_polyline
,这可能只是一个粗略的近似线。