Trouver un path / une route entre deux points sur MapKit dans l'iPhone

J'essaie de find le path entre deux endroits sur Mapkit. Tout ce que j'ai est deux endroits. Maintenant, je dois find le path exact entre ces points et tracer une ligne entre ces points en utilisant MapKit. J'ai parcouru plusieurs exemples dans lesquels ils utilisent des files .csv. Dans ce file .csv, ils ont stocké les valeurs de latitude et de longitude du path complet et de la ligne de dessin en fonction de ces valeurs.

Mais ici j'essaie de tracer une ligne sans connaître le path. Alors, y a-t-il un moyen de find dynamicment le path et de tracer une ligne?

Voici le code pour find le path et dessine la ligne entre deux endroits.

Pour implémenter la class ci-dessous:

_mapRecord = [[PSMapDirection alloc] initWithFrame:CGRectMake(0.0, 49.0, 320.0, 411.0)]; [self.view addSubview:_mapRecord]; 

MapDirection.h

 #import <UIKit/UIKit.h> #import <MapKit/MapKit.h> #import "RegexKitLite.h" @interface MapDirection : UIView<MKMapViewDelegate> { MKMapView* mapView; NSArray* routes; BOOL isUpdatingRoutes; } -(void) showRouteFrom: (MKAnnotation*) f to:(MKAnnotation*) t; @end 

MapDirection.m

 #import "MapDirection.h" @interface MapDirection() -(NSArray*) calculateRoutesFrom:(CLLocationCoordinate2D) from to: (CLLocationCoordinate2D) to; -(void) centerMap; @end - (id) initWithFrame:(CGRect) frame { self = [super initWithFrame:frame]; if (self != nil) { mapView = [[MKMapView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)]; mapView.showsUserLocation = NO; [mapView setDelegate:self]; [self addSubview:mapView]; } return self; } - (NSMutableArray *)decodePolyLine: (NSMutableSsortingng *)encoded { [encoded replaceOccurrencesOfSsortingng:@"\\\\" withSsortingng:@"\\" 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; } -(NSArray*) calculateRoutesFrom:(CLLocationCoordinate2D) f to: (CLLocationCoordinate2D) t { NSSsortingng* saddr = [NSSsortingng ssortingngWithFormat:@"%f,%f", f.latitude, f.longitude]; NSSsortingng* daddr = [NSSsortingng ssortingngWithFormat:@"%f,%f", t.latitude, t.longitude]; NSSsortingng* apiUrlStr = [NSSsortingng ssortingngWithFormat:@"http://maps.google.com/maps?output=dragdir&saddr=%@&daddr=%@", saddr, daddr]; NSURL* apiUrl = [NSURL URLWithSsortingng:apiUrlStr]; //NSLog(@"api url: %@", apiUrl); NSError* error = nil; NSSsortingng *apiResponse = [NSSsortingng ssortingngWithContentsOfURL:apiUrl encoding:NSASCIISsortingngEncoding error:&error]; NSSsortingng *encodedPoints = [apiResponse ssortingngByMatching:@"points:\\\"([^\\\"]*)\\\"" capture:1L]; return [self decodePolyLine:[encodedPoints mutableCopy]]; } -(void) centerMap { MKCoordinateRegion region; CLLocationDegrees maxLat = -90.0; CLLocationDegrees maxLon = -180.0; CLLocationDegrees minLat = 90.0; CLLocationDegrees minLon = 180.0; for(int idx = 0; idx < routes.count; idx++) { CLLocation* currentLocation = [routes objectAtIndex:idx]; if(currentLocation.coordinate.latitude > maxLat) maxLat = currentLocation.coordinate.latitude; if(currentLocation.coordinate.latitude < minLat) minLat = currentLocation.coordinate.latitude; if(currentLocation.coordinate.longitude > maxLon) maxLon = currentLocation.coordinate.longitude; if(currentLocation.coordinate.longitude < minLon) minLon = currentLocation.coordinate.longitude; } region.center.latitude = (maxLat + minLat) / 2.0; region.center.longitude = (maxLon + minLon) / 2.0; region.span.latitudeDelta = 0.01; region.span.longitudeDelta = 0.01; region.span.latitudeDelta = ((maxLat - minLat)<0.0)?100.0:(maxLat - minLat); region.span.longitudeDelta = ((maxLon - minLon)<0.0)?100.0:(maxLon - minLon); [mapView setRegion:region animated:YES]; } -(void) showRouteFrom: (MKAnnotation*) f to:(MKAnnotation*) t { if(routes) { [mapView removeAnnotations:[mapView annotations]]; } [mapView addAnnotation:f]; [mapView addAnnotation:t]; routes = [self calculateRoutesFrom:f.coordinate to:t.coordinate]; NSInteger numberOfSteps = routes.count; CLLocationCoordinate2D coordinates[numberOfSteps]; for (NSInteger index = 0; index < numberOfSteps; index++) { CLLocation *location = [routes objectAtIndex:index]; CLLocationCoordinate2D coordinate = location.coordinate; coordinates[index] = coordinate; } MKPolyline *polyLine = [MKPolyline polylineWithCoordinates:coordinates count:numberOfSteps]; [mapView addOverlay:polyLine]; [self centerMap]; } #pragma mark MKPolyline delegate functions - (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay { MKPolylineView *polylineView = [[MKPolylineView alloc] initWithPolyline:overlay]; polylineView.strokeColor = [UIColor purpleColor]; polylineView.lineWidth = 5.0; return polylineView; } @end 

Exemple de carte Itinéraire pour les points de départ – "41.967659, -87.627869" et les points de destination – "41.574361, -91.083069 "

Route de la carte

Voici la façon dont je suis capable de tracer la direction entre deux points (location).


Tout d'abord download GoogleMap SDK à partir de ce lien et intégrer dans votre application.

Maintenant key API requirejse et vous pouvez créer en tant que lignes direcsortingces données sur ce lien.

Ci-dessous sont le code qui dessine la direction sur google map entre deux locations.


 -(NSArray*) calculateRoutesFrom:(CLLocationCoordinate2D) f to: (CLLocationCoordinate2D) t { NSSsortingng* saddr = [NSSsortingng ssortingngWithFormat:@"%f,%f", f.latitude, f.longitude]; NSSsortingng* daddr = [NSSsortingng ssortingngWithFormat:@"%f,%f", t.latitude, t.longitude]; NSURL *url=[NSURL URLWithSsortingng:[NSSsortingng ssortingngWithFormat:@"http://maps.googleapis.com/maps/api/directions/json?origin=%@&destination=%@&sensor=false&avoid=highways&mode=driving",saddr,daddr]]; NSError *error=nil; NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ; [request setURL:url]; [request setHTTPMethod:@"POST"]; NSURLResponse *response = nil; NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error: &error]; NSSsortingng *responseSsortingng = [[NSSsortingng alloc] initWithData:responseData encoding:NSUTF8SsortingngEncoding]; NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:[responseSsortingng dataUsingEncoding:NSUTF8SsortingngEncoding] options:NSJSONWritingPrettyPrinted error:nil]; return [self decodePolyLine:[self parseResponse:dic]]; } - (NSSsortingng *)parseResponse:(NSDictionary *)response { NSArray *routes = [response objectForKey:@"routes"]; NSDictionary *route = [routes lastObject]; if (route) { NSSsortingng *overviewPolyline = [[route objectForKey: @"overview_polyline"] objectForKey:@"points"]; return overviewPolyline; } return @""; } -(NSMutableArray *)decodePolyLine:(NSSsortingng *)encodedStr { NSMutableSsortingng *encoded = [[NSMutableSsortingng alloc] initWithCapacity:[encodedStr length]]; [encoded appendSsortingng:encodedStr]; [encoded replaceOccurrencesOfSsortingng:@"\\\\" withSsortingng:@"\\" 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]; CLLocation *location = [[CLLocation alloc] initWithLatitude: [latitude floatValue] longitude:[longitude floatValue]]; [array addObject:location]; } return array; } - (void)loadMapViewWithDirection { float lat = 23.050671; float lng = 72.541351; GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:lat longitude:lng zoom:10]; GMSMapView * mapView = [GMSMapView mapWithFrame:CGRectMake(0, 75, 320, self.view.frame.size.height-kHeaderRect.size.height) camera:camera]; self.mapView.myLocationEnabled = YES; float sourceLatitude = 23.050671; float sourceLongitude = 72.541351; float destLatitude = 23.036138; float destLongitude = 72.603836; GMSMarker *sourceMarker = [[GMSMarker alloc] init]; marker.position = CLLocationCoordinate2DMake(sourceLatitude, sourceLongitude); marker.map = self.mapView; GMSMarker *destMarker = [[GMSMarker alloc] init]; marker.position = CLLocationCoordinate2DMake(destLatitude, destLongitude); marker.map = self.mapView; self.mapView.delegate = self; [self drawDirection:CLLocationCoordinate2DMake(sourceLatitude, sourceLongitude) and:CLLocationCoordinate2DMake(destLatitude, destLongitude)]; [self.view addSubview:self.mapView]; } - (void) drawDirection:(CLLocationCoordinate2D)source and:(CLLocationCoordinate2D) dest { GMSPolyline *polyline = [[GMSPolyline alloc] init]; GMSMutablePath *path = [GMSMutablePath path]; NSArray * points = [self calculateRoutesFrom:source to:dest]; NSInteger numberOfSteps = points.count; for (NSInteger index = 0; index < numberOfSteps; index++) { CLLocation *location = [points objectAtIndex:index]; CLLocationCoordinate2D coordinate = location.coordinate; [path addCoordinate:coordinate]; } polyline.path = path; polyline.strokeColor = [UIColor redColor]; polyline.strokeWidth = 2.f; polyline.map = self.mapView; // Copy the previous polyline, change its color, and mark it as geodesic. polyline = [polyline copy]; polyline.strokeColor = [UIColor greenColor]; polyline.geodesic = YES; polyline.map = self.mapView; } - (void)viewDidLoad { [super viewDidLoad]; [self loadMapViewWithDirection]; } 

Vous pouvez vous référer à ce code , il fait exactement ce que vous voulez.
EDIT: et cela aussi

Je ne pense pas que tu puisses le faire localement. Implémenter un algorithm pour find un path entre deux points GPS nécessite beaucoup de données d'input (données provenant des maps) et vous n'avez pas cela. Seul un fournisseur de maps peut se permettre d'implémenter un tel algorithm et exposer une API pour l'utiliser. Je pense que Google a une API routing, mais je n'ai pas joué avec ça …

https://developers.google.com/maps/documentation/directions/

Notez que les TOS disent que vous devez afficher les résultats sur une carte Google, vous devrez donc désactiver la fonctionnalité sur la prochaine version iOS