Search code examples
iosdecodegoogle-maps-sdk-ios

Google Maps decoded GMSPath incorrect iOS


So, I use the directions API in my app. However, when I decode the polyline from the response, it does not show up correctly. Here is my code:

    //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;
});

And here is the polyline:

enter image description here

As you can,see it does not follow the road properly. However, to me it seems as if there are not enough points to have proper bends.

EDIT: This only happens 50% of the time, sometimes it shows up correctly, sometimes it does not.

What could I be doing wrong?


Solution

  • Going by this (which is using the js API instead of the json API that you're using):

    Get a polyline from Google maps directions V3

    It looks like you should use the lines in each of the steps of the legs in the response, instead of the overview_polyline which is probably meant to be just a rough approximate line.