如何在MapView中获得两个给定坐标之间的最短路径?

时间:2017-07-18 10:27:20

标签: ios objective-c swift3

我无法在地图视图中的两个坐标之间找到 最短路径 。我搜索了堆栈溢出,但它向我显示了一些算法而不是地图视图的确切iOS代码。我如何获得它?

谢谢。

3 个答案:

答案 0 :(得分:1)

您可以使用Google Maps SDK提供的Directions API。 例: https://maps.googleapis.com/maps/api/directions/json?origin=lat,long&destination=lat1,lon1

它获取源和目标纬度和经度,并返回路径的JSON对象和每条路线的距离。您可以选择最短路线并进行映射。

答案 1 :(得分:0)

以下是Google api document的参考。使用api以及必需和可选参数尝试自己。使用 Google DirectionsService 非常有趣。

答案 2 :(得分:0)

@swati我已经实现谷歌地图找到这样的最短路径:请根据你改变代码和对象。

您还可以参考以下网址:Google Map Documentations

- (void)drawRoute:(CLLocationDegrees)lat和:(CLLocationDegrees)lng {

    if ([polyline isKindOfClass:[GMSPolyline class]]){

       polyline = nil;
       polyline.map = nil;
       currentPoly.map = nil;

    }
  [polyline setMap:nil];
   currentPoly.map = nil;


  CLLocation *LocationAtual = [[CLLocation alloc] initWithLatitude:lat longitude:lng];
  [self fetchPolylineWithOrigin:currentLocation destination:LocationAtual completionHandler:^(GMSPolyline *polyline1)
   {
      if(polyline1)
         polyline1.map = mapView;
   }];
} 
 -(void)fetchPolylineWithOrigin:(CLLocation )origin destination:(CLLocation )destination completionHandler:(void (^)(GMSPolyline *))completionHandler
 {
      NSString *originString = [NSString stringWithFormat:@"%f,%f", origin.coordinate.latitude, origin.coordinate.longitude];
      NSString *destinationString = [NSString stringWithFormat:@"%f,%f", destination.coordinate.latitude, destination.coordinate.longitude];
      NSString *directionsAPI = @"https://maps.googleapis.com/maps/api/directions/json?";
      NSString *directionsUrlString = [NSString stringWithFormat:@"%@&origin=%@&destination=%@&mode=driving", directionsAPI, originString, destinationString];
      NSURL *directionsUrl = [NSURL URLWithString:directionsUrlString];

      NSURLSessionDataTask *fetchDirectionsTask = [[NSURLSession sharedSession] dataTaskWithURL:directionsUrl completionHandler:
                                             ^(NSData data, NSURLResponse response, NSError *error)
                                             {
                                                 NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
                                                 if(error)
                                                 {
                                                     if(completionHandler)
                                                         completionHandler(nil);
                                                     return;
                                                 }
                                                routesArray = [json objectForKey:@"routes"];
                                                 dispatch_sync(dispatch_get_main_queue(), ^{
                                                    currentPoly.map = nil;
                                                     NSString *points;
                                                     if ([routesArray count] > 0)
                                                     {
                                                         NSDictionary *routeDict = [routesArray objectAtIndex:0];
                                                         NSDictionary *routeOverviewPolyline = [routeDict objectForKey:@"overview_polyline"];
                                                         points = [routeOverviewPolyline objectForKey:@"points"];
                                                     }
                                                     GMSPath *path = [GMSPath pathFromEncodedPath:points];
                                                     polyline = [GMSPolyline polylineWithPath:path];
                                                     polyline.strokeWidth = 4.f;
                                                     polyline.strokeColor = [UIColor colorWithRed:0.2043 green:0.6188 blue:0.9986 alpha:1.0000];
                                                     polyline.geodesic = YES;
                                                     polyline.map = mapView;
                                                     currentPoly = polyline;
                                                     [self distance:place_Id];
                                                     if(completionHandler)
                                                         completionHandler(polyline);
                                                 });
                                             }];
                                  [fetchDirectionsTask resume];
    }

=============================================== ==========================

  -(void)distance :(NSString*)placeId{

      NSString *mainURL = @"https://maps.googleapis.com/maps/api/place/details/json?";
      NSString *placeid = placeId;
      NSString *key =@"Your Google Api Key"; // Write here your google API Key here


      NSString *directionsUrlString = [NSString stringWithFormat:@"placeid=%@&key=%@",placeid, key];


      mainURL = [mainURL stringByAppendingString:directionsUrlString];
      NSURL *url = [NSURL URLWithString:mainURL];


      NSMutableURLRequest *urlRequest =
     [NSMutableURLRequest requestWithURL:url];
     [urlRequest setTimeoutInterval:30.0f];
     [urlRequest setHTTPMethod:@"GET"];
     NSOperationQueue *queue = [[NSOperationQueue alloc] init];
     [NSURLConnection sendAsynchronousRequest:urlRequest queue:queue
 completionHandler:^(NSURLResponse *response,
                     NSData *data,
                     NSError *error) {
     if ([data length] >0 && error == nil){

         NSMutableString *strResponse =[[NSMutableString alloc] initWithData:data encoding:NSUTF8StringEncoding];
         NSData *data = [strResponse dataUsingEncoding:NSUTF8StringEncoding];

         id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
         //NSLog(@"json=====%@",json);
         deatils_result = [json objectForKey:@"result"];

       }
       else if ([data length] == 0 && error == nil)
        {
         //NSLog(@"Nothing was downloaded.");
        }
       else if (error != nil)
       {

           // NSLog(@"Error happened = %@", error);
       }
   }];
 }