iOS - 具有 100 多个坐标的 Snap To Road API

Posted

技术标签:

【中文标题】iOS - 具有 100 多个坐标的 Snap To Road API【英文标题】:iOS - Snap To Road API with more than 100 coordinates 【发布时间】:2016-08-17 09:48:23 【问题描述】:

我知道如何使用 snap to road API 并解析响应、在地图上显示等。但是 snap to road API 有 100 个坐标/请求的限制。

假设我有一个包含 100 多个坐标的数组,并希望它们都捕捉到道路。

snap to road API docs 描述了一个解决方法,如果使用超过 100 个坐标,但它是 Java 代码(我认为),我并不真正理解它。

我如何在 Objective-C 中做到这一点?

在我的实现中,我通过从数组中获取 100 个坐标的范围来多次调用 snap to road api。然而,当在地图上绘制时,这会导致奇怪的折线:

这是我的代码:

-(void)getDirectionsFrom:(CLLocation*)startLocation to:(CLLocation*)endLocation

    //Create placemarks from the passed in locations
    MKPlacemark *start = [[MKPlacemark alloc] initWithCoordinate:locManager.location.coordinate addressDictionary:NULL];
    MKPlacemark *finsih = [[MKPlacemark alloc] initWithCoordinate:endLocation.coordinate addressDictionary:NULL];

    //Create direction request
    MKDirectionsRequest *request = [[MKDirectionsRequest alloc]init];
    [request setSource:[[MKMapItem alloc] initWithPlacemark:start]];
    [request setDestination:[[MKMapItem alloc] initWithPlacemark:finsih]];
    [request setTransportType:MKDirectionsTransportTypeAutomobile];

    //Calculate directions
    MKDirections *direction = [[MKDirections alloc]initWithRequest:request];

    [direction calculateDirectionsWithCompletionHandler: ^(MKDirectionsResponse *response, NSError *error) 

        if (error) 
            NSLog(@"Error is %@",error);
        

        else 

            MKRoute *route = [response.routes firstObject];

            NSUInteger pointCount = route.polyline.pointCount;

            //Allocate a C array to hold this many points/coordinates...
            CLLocationCoordinate2D *routeCoordinates = malloc(pointCount * sizeof(CLLocationCoordinate2D));

            //Get the coordinates (all of them)...
            [route.polyline getCoordinates:routeCoordinates range:NSMakeRange(0, pointCount)];

            NSMutableArray *locationsArray = [[NSMutableArray alloc] init];

            CLLocation *lastLocation = [[CLLocation alloc] init];


            //Call snap to road with 100 locations at a time
            for (int start = 0; start < pointCount; start += 99) 
                [locationsArray removeAllObjects];
                NSInteger length = MIN(99, pointCount-start);
                if(start != 0)
                    [locationsArray addObject:lastLocation];
                
                for(int i = start;i<start+length;i++)
                    CLLocationCoordinate2D loc2D = routeCoordinates[i];
                    CLLocation *location = [[CLLocation alloc] initWithLatitude:loc2D.latitude longitude:loc2D.longitude];
                    [locationsArray addObject:location];
                

                lastLocation = [locationsArray lastObject];
                [self snapPathToRoad:locationsArray];
            

            //Free the memory used by the C array
            free(routeCoordinates);

        
    ];




-(void)snapPathToRoad:(NSMutableArray*)passedInArray

    //Create string to store coordinates in for the URL
    NSString *tempcoordinatesForURL = @"";

    //Append tempcoordinatesForURL string by the coordinates in the right format
    for(int i = 0;i<[passedInArray count];i++)

        CLLocationCoordinate2D coordinates = [[passedInArray objectAtIndex:i] coordinate];

        NSString *coordinatesString = [NSString stringWithFormat:@"|%f,%f|",coordinates.latitude,coordinates.longitude];

        tempcoordinatesForURL = [tempcoordinatesForURL stringByAppendingString:coordinatesString];
    

    //Remove unnecessary charchters from tempcoordinatesForURL
    NSString *coordinatesForURL = [[tempcoordinatesForURL substringToIndex:[tempcoordinatesForURL length]-1] stringByReplacingOccurrencesOfString:@"||" withString:@"|"];

    //Create url by removing last charachter from coordinatesForURL string
    NSString *urlPath = [NSString stringWithFormat:@"https://roads.googleapis.com/v1/snapToRoads?path=%@&interpolate=true&key=AIzaSyDrtHA-AMiVVylUPcp46_Vf1eZJJFBwRCY",[coordinatesForURL substringFromIndex:1]];

    //Remove unsupproted charchters from urlPath and create an NSURL
    NSString *escapedUrlPath = [urlPath stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSURL *url = [NSURL URLWithString:escapedUrlPath];

    //Create request
    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    //Send request to server
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) 

        //If response, parse JSON
        if(response)

            //Dictionary with the whole JSON file
            NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

            //Array of snapped points from the JSON
            NSArray *snappedPoints = [result objectForKey:@"snappedPoints"];

            //Loop through the snapped points array and add each coordinate to the path
            for (int i = 0; i<[snappedPoints count]; i++) 
                NSDictionary *location = [[snappedPoints objectAtIndex:i] objectForKey:@"location"];

                double latitude = [[location objectForKey:@"latitude"] doubleValue];
                double longitude = [[location objectForKey:@"longitude"] doubleValue];

                [pathToDraw addCoordinate:CLLocationCoordinate2DMake(latitude, longitude)];

            

            //As this method is called multiple times, clear the previous polylines so only the final one will be visible on the map
            [self.mapView clear];

            //Draw polyline with path
            GMSPolyline *polyline = [GMSPolyline polylineWithPath:pathToDraw];
            polyline.map = self.mapView;
            polyline.strokeColor = [UIColor darkGrayColor];
            polyline.strokeWidth = 6;

        

        //If error, log it
        else if(connectionError)
            NSLog(@"%@",connectionError);
        

    ];


patToDrawGMSMutablePath ivar”

【问题讨论】:

【参考方案1】:

最终,我发现了问题所在。

如果异步调用多个请求,并非所有请求都会同时完成。因为它们每个都将坐标添加到相同的路径,例如具有较少坐标的请求将更快完成,尽管它们被稍后调用。这会导致添加到路径中的坐标顺序错误。

【讨论】:

以上是关于iOS - 具有 100 多个坐标的 Snap To Road API的主要内容,如果未能解决你的问题,请参考以下文章

OpenJudge百炼习题解答(C++)--题4072:判断多个点是否在同一直线

在 snap 中使用具有持久数据类型的类型安全路由

在matlab中怎样在同一坐标对多个函数归一化

具有双坐标的多边形

Forge Viewer 加载具有共享坐标的多个 Revit 模型

比TensorFlow云快46倍!IBM用Snap ML和Tesla V100秀肌肉