如何找到两个坐标之间的道路距离并在相同点之间形成折线?

时间:2015-02-06 06:09:27

标签: ios xcode6 mapkit

我想找到两个坐标之间的道路距离。首先,我从用户那里获取源和目的地,然后使用googleMap api找到坐标。

我能够找到坐标和空中距离,但我无法找到道路距离并在它们之间绘制折线。谷歌上可用的每种方法都适用于较旧的xcode,xcode 6不支持。

  

我用于查找坐标的方法

-(CLLocationCoordinate2D)FindCoordinates:(NSString *)place
{

NSString *addresss = place;
NSString *esc_addr = [addresss stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
NSString *req = [NSString stringWithFormat: @"http://maps.google.com/maps/api/geocode/json?sensor=false&address=%@", esc_addr];

NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:req]];


NSDictionary  *googleResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

NSDictionary *resultsDict = [googleResponse valueForKey:  @"results"];   // get the results dictionary
NSDictionary *geometryDict = [   resultsDict valueForKey: @"geometry"];   // geometry dictionary within the  results dictionary
NSDictionary *locationDict = [  geometryDict valueForKey: @"location"];   // location dictionary within the geometry dictionary

// nslo (@”– returning latitude & longitude from google –”);

NSArray *latArray = [locationDict valueForKey: @"lat"]; NSString *latString = [latArray lastObject];     // (one element) array entries provided by the json parser
NSArray *lngArray = [locationDict valueForKey: @"lng"]; NSString *lngString = [lngArray lastObject];     // (one element) array entries provided by the json parser

myLocation.latitude = [latString doubleValue];     // the json parser uses NSArrays which don’t support “doubleValue”
myLocation.longitude = [lngString doubleValue];

return myLocation;

}
  

我用来寻找距离的方法

-(IBAction)getLocation:(id)sender
{
sourceLocation = [self FindCoordinates:source1.text];
NSLog(@"%@",[NSString stringWithFormat:@"Source lat:%f Source lon:%f",sourceLocation.latitude,sourceLocation.longitude]);
destinationLocation = [self getMe:destination1.text];
NSLog(@"%@",[NSString stringWithFormat:@"Desti lat:%f Desti lon:%f",destinationLocation.latitude,destinationLocation.longitude]);

CLLocation *loc1 = [[CLLocation alloc] initWithLatitude:sourceLocation.latitude longitude:sourceLocation.longitude];
CLLocation *loc2 = [[CLLocation alloc] initWithLatitude:destinationLocation.latitude longitude:destinationLocation.longitude];


CLLocationDistance distance = [loc1 distanceFromLocation:loc2];
NSLog(@"%@",[NSString stringWithFormat:@"Distance iin KMeteres %f",distance/1000]); // Gives me air distance


MKPlacemark *source = [[MKPlacemark alloc]initWithCoordinate:CLLocationCoordinate2DMake(37.776142, -122.424774) addressDictionary:[NSDictionary dictionaryWithObjectsAndKeys:@"",@"", nil] ]; // Not able to modify these cordinates

MKMapItem *srcMapItem = [[MKMapItem alloc]initWithPlacemark:source];
[srcMapItem setName:@""];

MKPlacemark *destination = [[MKPlacemark alloc]initWithCoordinate:CLLocationCoordinate2DMake(37.73787, -122.373962) addressDictionary:[NSDictionary dictionaryWithObjectsAndKeys:@"",@"", nil] ];

MKMapItem *distMapItem = [[MKMapItem alloc]initWithPlacemark:destination];
[distMapItem setName:@""];

MKDirectionsRequest *request = [[MKDirectionsRequest alloc]init];
[request setSource:srcMapItem];
[request setDestination:distMapItem];
[request setTransportType:MKDirectionsTransportTypeWalking];

MKDirections *direction = [[MKDirections alloc]initWithRequest:request];

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

    NSLog(@"response = %@",response);
    NSArray *arrRoutes = [response routes];
    [arrRoutes enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {

        MKRoute *rout = obj;

        MKPolyline *line = [rout polyline];
        [map addOverlay:line];
        NSLog(@"Rout Name : %@",rout.name);
        NSLog(@"Total Distance (in Meters) :%f",rout.distance);

        NSArray *steps = [rout steps];

        NSLog(@"Total Steps : %lu",(unsigned long)[steps count]);

        [steps enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            NSLog(@"Rout Instruction : %@",[obj instructions]);
            NSLog(@"Rout Distance : %f",[obj distance]);
        }];
    }];
}];



}

如何绘制折线。

1 个答案:

答案 0 :(得分:1)

您必须在iOS 8中使用MKPolylineRenderer

以下是通过点按位置添加MKPolyline的代码,您可以获得帮助。

<强> Pin.h

#import <Foundation/Foundation.h>
@import MapKit;

@interface Pin : NSObject <MKAnnotation> 

@property (nonatomic, readonly) CLLocationCoordinate2D coordinate;
@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *subtitle;

- (id)initWithCoordinate:(CLLocationCoordinate2D)newCoordinate;

@end

<强> Pin.m

#import "Pin.h"

@implementation Pin

- (id)initWithCoordinate:(CLLocationCoordinate2D)newCoordinate {

    self = [super init];
    if (self) {
        _coordinate = newCoordinate;
        _title = @"Hello";
        _subtitle = @"Are you still there?";
    }
    return self;
}

@end

<强> ViewController.h

#import <UIKit/UIKit.h>
@import MapKit;

@interface ViewController : UIViewController <MKMapViewDelegate>

@end

<强> ViewController.m

#import "ViewController.h"
#import "Pin.h"

@interface ViewController ()

@property (strong, nonatomic) IBOutlet MKMapView *mapView;
@property (nonatomic, strong) NSMutableArray *allPins;
@property (nonatomic, strong) MKPolylineRenderer *lineView;
@property (nonatomic, strong) MKPolyline *polyline;

- (IBAction)drawLines:(id)sender;
- (IBAction)undoLastPin:(id)sender;

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.allPins = [[NSMutableArray alloc]init];

    // add a long press gesture
    UILongPressGestureRecognizer *recognizer = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(addPin:)];
    recognizer.minimumPressDuration = 0.5;
    [self.mapView addGestureRecognizer:recognizer];
}

// let the user add their own pins

- (void)addPin:(UIGestureRecognizer *)recognizer {

    if (recognizer.state != UIGestureRecognizerStateBegan) {
        return;
    }

    // convert touched position to map coordinate
    CGPoint userTouch = [recognizer locationInView:self.mapView];
    CLLocationCoordinate2D mapPoint = [self.mapView convertPoint:userTouch toCoordinateFromView:self.mapView];

    // and add it to our view and our array
    Pin *newPin = [[Pin alloc]initWithCoordinate:mapPoint];
    [self.mapView addAnnotation:newPin];
    [self.allPins addObject:newPin];

    [self drawLines:self];

}

- (IBAction)drawLines:(id)sender {

    // HACK: for some reason this only updates the map view every other time
    // and because life is too frigging short, let's just call it TWICE

    [self drawLineSubroutine];
    [self drawLineSubroutine];

}

- (IBAction)undoLastPin:(id)sender {

    // grab the last Pin and remove it from our map view
    Pin *latestPin = [self.allPins lastObject];
    [self.mapView removeAnnotation:latestPin];
    [self.allPins removeLastObject];

    // redraw the polyline
    [self drawLines:self];
}

- (void)drawLineSubroutine {

    // remove polyline if one exists
    [self.mapView removeOverlay:self.polyline];

    // create an array of coordinates from allPins
    CLLocationCoordinate2D coordinates[self.allPins.count];
    int i = 0;
    for (Pin *currentPin in self.allPins) {
        coordinates[i] = currentPin.coordinate;
        i++;
    }

    // create a polyline with all cooridnates
    MKPolyline *polyline = [MKPolyline polylineWithCoordinates:coordinates count:self.allPins.count];
    [self.mapView addOverlay:polyline];
    self.polyline = polyline;

    // create an MKPolylineView and add it to the map view
    self.lineView = [[MKPolylineRenderer alloc]initWithPolyline:self.polyline];
    self.lineView.strokeColor = [UIColor redColor];
    self.lineView.lineWidth = 5;

    // for a laugh: how many polylines are we drawing here?
    self.title = [[NSString alloc]initWithFormat:@"%lu", (unsigned long)self.mapView.overlays.count];

}

- (MKPolylineRenderer *)mapView:(MKMapView *)mapView viewForOverlay:(id<MKOverlay>)overlay {

    return self.lineView;
}

@end

获取距离

CLLocationDistance dist = [from distanceFromLocation:current];