我正在使用MapKit api来获取地图上的当前位置,并在两个位置之间绘制路线。我还希望获得其路线之间的所有主要站点。 我使用下面的函数来获取两个位置之间的路径
- (NSArray*)getRoutePointFrom:(MyLocation*)origin to:(MyLocation*)destination
{
NSString* saddr = [NSString stringWithFormat:@"%f,%f", origin.coordinate.latitude, origin.coordinate.longitude];
NSString* daddr = [NSString stringWithFormat:@"%f,%f", destination.coordinate.latitude, destination.coordinate.longitude];
NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:@"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];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
SBJsonParser *json=[[SBJsonParser alloc] init];
NSDictionary *dic=[json objectWithString:responseString error:nil];
NSDictionary *nextdic=[dic valueForKey:@"routes"];
NSDictionary *legdic=[nextdic valueForKey:@"legs"];
NSDictionary *stepdic=[legdic valueForKey:@"steps"];
NSArray *array=[[NSArray alloc] initWithArray:[[stepdic valueForKey:@"polyline"] valueForKey:@"points"]];
NSString *string=[NSString stringWithFormat:@"%@",[[array objectAtIndex:0] objectAtIndex:0]];
return [self decodePolyLine:[string mutableCopy]];
}
-(NSMutableArray *)decodePolyLine:(NSString *)encodedStr
{
NSMutableString *encoded = [[NSMutableString alloc] initWithCapacity:[encodedStr length]];
[encoded appendString:encodedStr];
[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];
}
NSLog(@"array in decode polygon is %@",array);
return array;
}
但它不起作用。 ..
对此有所帮助 谢谢!...
答案 0 :(得分:5)
有几次问过这个问题。我想你正在从http://iosguy.com/2012/05/22/tracing-routes-with-mapkit/获取代码 您还可以查看该问题:Plotting Route with Multiple Points in iOS
您也可以从http://iosboilerplate.com获取代码并为此做出贡献。
最后但并非最不重要的是,有一个框架可以帮助你做一小笔钱(但没有什么比你需要做的那样): http://www.cocoacontrols.com/controls/mtdirectionskit
答案 1 :(得分:4)
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
@interface ViewController : UIViewController<MKMapViewDelegate>
{
NSData *alldata;
NSMutableDictionary *data1;
NSMutableArray *RouteLocation;
NSMutableArray *RouteName;
}
@property (strong, nonatomic) IBOutlet MKMapView *mapview;
@property (nonatomic, retain) MKPolyline *routeLine;
@property (nonatomic, retain) MKPolylineView *routeLineView;
-(void)LoadMapRoute;
@end
#import "ViewController.h"
@implementation ViewController
@synthesize mapview,routeLine,routeLineView;
- (void)viewDidLoad {
[super viewDidLoad];
self.mapview.delegate = self;
// Do any additional setup after loading the view, typically from a nib.
RouteName = [[NSMutableArray alloc] initWithObjects:@"Ahmedabad",@"Rajkot", nil];
RouteLocation = [[NSMutableArray alloc] initWithObjects:@"23.0300,72.5800",@"22.3000,70.7833", nil];
[self LoadMapRoute];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
//-------------------------------------
// ************* Map ******************
//-------------------------------------
-(void)LoadMapRoute
{
MKCoordinateSpan span = MKCoordinateSpanMake(0.8, 0.8);
MKCoordinateRegion region;
region.span = span;
region.center= CLLocationCoordinate2DMake(23.0300,72.5800);
// Distance between two address
NSArray *coor1=[[RouteLocation objectAtIndex:0] componentsSeparatedByString:@","];
CLLocation *locA = [[CLLocation alloc] initWithLatitude:[[coor1 objectAtIndex:0] doubleValue] longitude:[[coor1 objectAtIndex:1] doubleValue]];
NSArray *coor2=[[RouteLocation objectAtIndex:1] componentsSeparatedByString:@","];
CLLocation *locB = [[CLLocation alloc] initWithLatitude:[[coor2 objectAtIndex:0] doubleValue] longitude:[[coor2 objectAtIndex:1] doubleValue]];
CLLocationDistance distance = [locA distanceFromLocation:locB];
NSLog(@"Distance :%.0f Meters",distance);
NSString *baseUrl = [NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/directions/json?origin=%@&destination=%@&sensor=true", [RouteLocation objectAtIndex:0],[RouteLocation objectAtIndex:1] ];
NSURL *url = [NSURL URLWithString:baseUrl];
alldata = [[NSData alloc] initWithContentsOfURL:url];
NSError *err;
data1 =[NSJSONSerialization JSONObjectWithData:alldata options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:&err];
NSString *overviewPolyline = [[[[data1 objectForKey:@"routes"] objectAtIndex:0] objectForKey:@"overview_polyline"] objectForKey:@"points"];
NSArray *path = [self decodePolyLine:overviewPolyline];
if (err)
{
NSLog(@" %@",[err localizedDescription]);
}
NSInteger numberOfSteps = path.count;
CLLocationCoordinate2D coordinates[numberOfSteps];
for (NSInteger index = 0; index < numberOfSteps; index++) {
CLLocation *location = [path objectAtIndex:index];
CLLocationCoordinate2D coordinate = location.coordinate;
coordinates[index] = coordinate;
}
MKPolyline *polyLine = [MKPolyline polylineWithCoordinates:coordinates count:numberOfSteps];
[self.mapview addOverlay:polyLine];
// MKPolyline *polyLine = [MKPolyline polylineWithCoordinates:path count: path.count];
// [self.mapview addOverlay:polyLine];
// [self.mapview setRegion:region animated:YES];
}
- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay
{
MKPolylineView *polylineView = [[MKPolylineView alloc] initWithPolyline:overlay];
polylineView.strokeColor = [UIColor colorWithRed:204/255. green:45/255. blue:70/255. alpha:1.0];
polylineView.lineWidth = 5;
return polylineView;
}
-(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;
}
@end