2016-04-23 49 views
0

我知道如何使用捕捉道路API並解析響應,在地圖上顯示它等等。但是,道路API的捕捉具有100個座標的限制/請求。iOS - 超過100個座標的捕捉道路API

比方說,我有一個100 +座標的數組,並希望他們所有人都能對準道路。

捕捉道路API docs描述了一個解決方法,如果使用超過100多個座標,但是它是Java代碼(我認爲),但我不太瞭解它。

我該如何在Objective-C中做到這一點?

在我的實現中,我通過從我的數組中獲取100個座標的範圍來多次調用道路API的捕捉。然而,這導致奇怪的折線,在地圖上繪製: enter image description here

這裏是我的代碼:

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

    }]; 

} 

patToDraw是一個GMSMutablePath伊娃」

回答

0

最終,我發現這個問題。

如果多個請求異步調用,並非所有請求都會同時完成。因爲它們中的每一個都將座標添加到相同的路徑,所以例如具有較少座標的請求將盡快完成,儘管它們稍後被調用。這會導致按錯誤順序將座標添加到路徑中。