2015-02-06 2 views
0

Я хочу найти расстояние между двумя координатами. Во-первых, я беру источник и получатель от пользователя, а затем используя googleMap api, я нахожу координаты.Как найти расстояние между двумя координатами и сделать полилинию между одними и теми же точками?

Я могу найти координаты и воздушное расстояние, но я не могу найти расстояние до дороги и нарисовать полилинию между ними. Каждый метод, доступный на Google для старшего 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

Вы должны использовать MKPolylineRenderer для прошивки 8

Ниже приводится код для добавления 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]; 
+0

pin.h является sublcass из WAHT? означает, что я даю во время создания этого класса. –

+0

Это «NSObject». Вам нужно создать два класса. pin.h и pin.m в вашем проекте. Я добавил код. @Dalvik –

+0

Я скопировал ваш весь код, как есть .. но при нажатии кнопки ничего не происходит –

Смежные вопросы