简体   繁体   English

如何找到两个坐标之间的道路距离并在相同点之间绘制多段线?

[英]How to find road distance between two Coordinates and make a polyline between same points?

I want to find road distance between two coordinates. 我想找到两个坐标之间的道路距离。 Firstly i am taking source and destination from user and then using googleMap api i find the coordinates. 首先,我从用户那里获取源和目的地,然后使用googleMap API查找坐标。

I am able to find coordinates and air distance but i am unable to find road distance and draw a polyline between them. 我能够找到坐标和空中距离,但无法找到道路距离并在它们之间绘制折线。 Every method available on google is for older xcode and not supported on xcode 6. Google上可用的每种方法都适用于较早的xcode,xcode 6上不支持。

Method i am using for finding coordinates 我用于查找坐标的方法

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

}

method i am using for finding distance 我用来寻找距离的方法

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



}

How can draw a polyline also. 怎么也可以画一条折线。

You have to use MKPolylineRenderer for iOS 8 您必须为iOS 8使用MKPolylineRenderer

Following is the code for adding MKPolyline by tapping on locations may you get help. 以下是通过点击位置添加MKPolyline的代码,您可能会获得帮助。

Pin.h 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 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 ViewController.h

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

@interface ViewController : UIViewController <MKMapViewDelegate>

@end

ViewController.m 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

Get distance by 取得距离

CLLocationDistance dist = [from distanceFromLocation:current];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM