在Google地图上创建长途路径时应用程序崩溃

时间:2015-07-21 07:41:21

标签: ios google-maps

我正在开发一个我需要两个位置之间路径的应用程序。 我实现了一些代码。这对于短距离路径来说很好,但是当我创建像印度拉贾斯坦邦的斋浦尔到Jorhat,印度Aasam这样的长距离路径时,我的应用程序就崩溃了。

这是我的代码

-(void)findPath{
[rectangle setMap:nil];


NSString* str = [NSMutableString stringWithFormat:@"http://maps.googleapis.com/maps/api/directions/json?origin=%@&destination=%@&sensor=true",  self.FromSearch, self.toSearch];

if (_travelMode==UICGTravelModeWalking) {
    str=[str stringByAppendingFormat:@"&mode=walking"];
}

NSURL *url=[[NSURL alloc]initWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];

NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

NSArray* latestRoutes = [json objectForKey:@"routes"];

NSString *points=[[[latestRoutes objectAtIndex:0] objectForKey:@"overview_polyline"] objectForKey:@"points"];
if ([latestRoutes isKindOfClass:[NSArray class]]&&latestRoutes.count==0) {
    UIAlertView *alrt=[[UIAlertView alloc]initWithTitle:@"Alert" message:@"didn't find direction" delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
    [alrt show];
    return;
}
arrDistance =[[[json valueForKeyPath:@"routes.legs.steps.distance.text"] objectAtIndex:0]objectAtIndex:0];
totalDuration = [[[json valueForKeyPath:@"routes.legs.duration.text"] objectAtIndex:0]objectAtIndex:0];
totalDistance = [[[json valueForKeyPath:@"routes.legs.distance.text"] objectAtIndex:0]objectAtIndex:0];
arrDescription =[[[json valueForKeyPath:@"routes.legs.steps.html_instructions"] objectAtIndex:0] objectAtIndex:0];
dictRouteInfo=[NSDictionary dictionaryWithObjectsAndKeys:totalDistance,@"totalDistance",totalDuration,@"totalDuration",arrDistance ,@"distance",arrDescription,@"description", nil];
double srcLat=[[[[json valueForKeyPath:@"routes.legs.start_location.lat"] objectAtIndex:0] objectAtIndex:0] doubleValue];
double srcLong=[[[[json valueForKeyPath:@"routes.legs.start_location.lng"] objectAtIndex:0] objectAtIndex:0] doubleValue];
totalLat = [[NSMutableArray alloc]init];
totalLong = [[NSMutableArray alloc]init];
  //for (int i = 0; i<arrDistance.count; i++) {
    totalLat = [[[json valueForKeyPath:@"routes.legs.steps.start_location.lat"] objectAtIndex:0] objectAtIndex:0];
totalLong = [[[json valueForKeyPath:@"routes.legs.steps.start_location.lng"] objectAtIndex:0] objectAtIndex:0];

[self saveInfoForPath];

 // }


CLLocationCoordinate2D location;
location.latitude = srcLat;
location.longitude = srcLong;
 // mapView.camera = [GMSCameraPosition cameraWithTarget:location

                                           //     zoom:10];
  //GMSCoordinateBounds *bounds = [[GMSCoordinateBounds alloc]initWithPath:<#(GMSPath *)#>]
 // [[GMSCoordinateBounds alloc] initWithCoordinate:vancouver coordinate:calgary];







@try {
    // TODO: better parsing. Regular expression?

    NSArray *temp= [self decodePolyLine:[points mutableCopy]];

    GMSMutablePath *path = [GMSMutablePath path];


    for(int idx = 0; idx < [temp count]; idx++)
    {
        CLLocation *location=[temp objectAtIndex:idx];

        [path addCoordinate:location.coordinate];

    }
    // create the polyline based on the array of points.

    rectangle = [GMSPolyline polylineWithPath:path];

    rectangle.strokeWidth=5.0;

    rectangle.map = mapView;
    GMSCoordinateBounds *bounds = [[GMSCoordinateBounds alloc]initWithPath:path];
    [mapView moveCamera:[GMSCameraUpdate fitBounds:bounds]];


}
@catch (NSException * e) {
    // TODO: show error
}



}

decodePolyline()方法编码

-(NSMutableArray *)decodePolyLine: (NSMutableString *)encoded {
[encoded replaceOccurrencesOfString:@"\\\\" withString:@"\\"
                            options:NSLiteralSearch
                              range:NSMakeRange(0, [encoded length])];
NSInteger len = [encoded length];
NSInteger index = 0;
NSMutableArray *array = [[NSMutableArray alloc] init] ;
NSInteger lat=0;
NSInteger 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] ;
    printf("[%f,", [latitude doubleValue]);
    printf("%f]", [longitude doubleValue]);
    CLLocation *loc = [[CLLocation alloc] initWithLatitude:[latitude floatValue] longitude:[longitude floatValue]] ;
    [array addObject:loc];
}

return array;
  }

我该怎么办?请建议。

1 个答案:

答案 0 :(得分:1)

您可以尝试使用pathFromEncodedPath方法代替decodePolyLine来从encodeString获取路径。

NSString *points=[[[latestRoutes objectAtIndex:0] objectForKey:@"overview_polyline"] objectForKey:@"points"];
polyline = [GMSPolyline polylineWithPath: [GMSPath pathFromEncodedPath: points]];
polyline.map = mapView;
polyline.strokeColor = [UIColor colorWithRed:0/255.0 green:4/255.0 blue:255/255.0 alpha:1.0];
polyline.strokeWidth = 4.0f;