如何绘制从当前位置到我在 mapView 中设置的注释图钉的路径?
how do i draw a path from my current location to the annotation pin i have set in my mapView?
我创建了一个 mapView(抱歉,我将我的 outlet 命名为 mapKit 而不是 mapView)。我获取了当前位置,并手动将注释图钉设置到某个位置。现在我需要的是只要我点击注释针(请准确地在注释针上,而不是 calloutAccessoryButton)我需要找到一条路径,可能使用从我当前位置到注释针的 polyPath。不完全像方向,只是路径,多边形叠加。请查看我的代码并帮助我。
- (void)viewDidLoad {
[super viewDidLoad];
locationManager = [[CLLocationManager alloc] init];
[locationManager requestWhenInUseAuthorization];
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.delegate = self;
[locationManager startUpdatingLocation];
MKPointAnnotation *myAnnotation = [[MKPointAnnotation alloc]init];
CLLocationCoordinate2D pinCoordinate;
pinCoordinate.latitude = 51.49795;
pinCoordinate.longitude = -0.174056;
myAnnotation.coordinate = pinCoordinate;
myAnnotation.title = @"Matthews Pizza";
myAnnotation.subtitle = @"Best Pizza in Town";
[self.mapKit addAnnotation:myAnnotation];
// myAnnotation.coordinate = CLLocationCoordinate2DMake(51.49795, -0.174056);
// Do any additional setup after loading the view.
}
-(void)checkStatus{
CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
if (status==kCLAuthorizationStatusNotDetermined) {
NSLog(@"Not Determined");
}
if (status==kCLAuthorizationStatusDenied) {
NSLog(@"Denied");
}
if (status==kCLAuthorizationStatusRestricted) {
NSLog(@"Restricted");
}
if (status==kCLAuthorizationStatusAuthorizedAlways) {
NSLog(@"Always Allowed");
}
if (status==kCLAuthorizationStatusAuthorizedWhenInUse) {
NSLog(@"NWhen In Use Allowed");
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)viewWillAppear:(BOOL)animated{
}
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 800, 800);
[self.mapKit setRegion:[self.mapKit regionThatFits:region] animated:YES];
}
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(@"didFailWithError: %@", error);
UIAlertView *errorAlert = [[UIAlertView alloc]
initWithTitle:@"Error" message:@"Failed to Get Your Location" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[errorAlert show];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSLog(@"didUpdateToLocation: %@", newLocation);
CLLocation *currentLocation = newLocation;
if (currentLocation != nil) {
NSLog(@"%@",[NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude]);
NSLog(@"%@",[NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude]);
}
}
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
// If it's the user location, just return nil.
if ([annotation isKindOfClass:[MKUserLocation class]])
return nil;
// Handle any custom annotations.
if ([annotation isKindOfClass:[MKPointAnnotation class]])
{
// Try to dequeue an existing pin view first.
MKAnnotationView *pinView = (MKAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:@"CustomPinAnnotationView"];
if (!pinView)
{
// If an existing pin view was not available, create one.
pinView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"CustomPinAnnotationView"];
pinView.canShowCallout = YES;
pinView.image = [UIImage imageNamed:@"ic_map"];
pinView.calloutOffset = CGPointMake(0, 32);
UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
pinView.rightCalloutAccessoryView = rightButton;
} else {
pinView.annotation = annotation;
}
return pinView;
}
return nil;
}
-(void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control {
id <MKAnnotation> annotation = [view annotation];
if ([annotation isKindOfClass:[MKPointAnnotation class]])
{
NSLog(@"Clicked Pizza Shop");
}
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Disclosure Pressed" message:@"Click Cancel to Go Back" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
[alertView show];
}
当点击 Annotation pin 时委托方法将调用
-(void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view
{
NSLog(@"Latitude: %f", view.annotation.coordinate.latitude);
NSLog(@"Longitude: %f", view.annotation.coordinate.longitude);
self.annotationViewCoordinate = view.annotation.coordinate;
[self GetDirections:view.annotation.coordinate];
}
绘制路径
- (void)GetDirections:(CLLocationCoordinate2D)locationCoordinate
{
MKPlacemark *aPlcSource = [[MKPlacemark alloc] initWithCoordinate:self.mapView.userLocation.coordinate addressDictionary:[NSDictionary dictionaryWithObjectsAndKeys:@"",@"", nil]];
MKPlacemark *aPlcDest = [[MKPlacemark alloc] initWithCoordinate:locationCoordinate addressDictionary:[NSDictionary dictionaryWithObjectsAndKeys:@"",@"", nil]];
MKMapItem *mpItemSource = [[MKMapItem alloc] initWithPlacemark:aPlcSource];
[mpItemSource setName:@"Source"];
MKMapItem *mpItemDest = [[MKMapItem alloc] initWithPlacemark:aPlcDest];
[mpItemDest setName:@"Dest"];
MKDirectionsRequest *aDirectReq = [[MKDirectionsRequest alloc] init];
[aDirectReq setSource:mpItemSource];
[aDirectReq setDestination:mpItemDest];
[aDirectReq setTransportType:MKDirectionsTransportTypeAutomobile];
MKDirections *aDirections = [[MKDirections alloc] initWithRequest:aDirectReq];
[aDirections calculateDirectionsWithCompletionHandler:^(MKDirectionsResponse *response, NSError *error) {
if (error) {
NSLog(@"Error :: %@",error);
}
else{
NSArray *aArrRoutes = [response routes];
NSLog(@"Routes :: %@",aArrRoutes);
[self.mapView removeOverlays:self.mapView.overlays];
[aArrRoutes enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
MKRoute *aRoute = obj;
[self.mapView addOverlay:aRoute.polyline];
NSLog(@"Route Name : %@",aRoute.name);
NSLog(@"Total Distance (in Meters) :%f",aRoute.distance);
NSArray *aArrSteps = [aRoute steps];
NSLog(@"Total Steps : %lu",(unsigned long)[aArrSteps count]);
[aArrSteps enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSLog(@"Rout Instruction : %@",[obj instructions]);
NSLog(@"Rout Distance : %f",[obj distance]);
}];
}];
}
}];
}
当用户位置移动时
你可以调用方法
- (void)GetDirections:(CLLocationCoordinate2D)locationCoordinate
来自方法
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
[self GetDirections:self.annotationViewCoordinate];
}
我创建了一个 mapView(抱歉,我将我的 outlet 命名为 mapKit 而不是 mapView)。我获取了当前位置,并手动将注释图钉设置到某个位置。现在我需要的是只要我点击注释针(请准确地在注释针上,而不是 calloutAccessoryButton)我需要找到一条路径,可能使用从我当前位置到注释针的 polyPath。不完全像方向,只是路径,多边形叠加。请查看我的代码并帮助我。
- (void)viewDidLoad {
[super viewDidLoad];
locationManager = [[CLLocationManager alloc] init];
[locationManager requestWhenInUseAuthorization];
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.delegate = self;
[locationManager startUpdatingLocation];
MKPointAnnotation *myAnnotation = [[MKPointAnnotation alloc]init];
CLLocationCoordinate2D pinCoordinate;
pinCoordinate.latitude = 51.49795;
pinCoordinate.longitude = -0.174056;
myAnnotation.coordinate = pinCoordinate;
myAnnotation.title = @"Matthews Pizza";
myAnnotation.subtitle = @"Best Pizza in Town";
[self.mapKit addAnnotation:myAnnotation];
// myAnnotation.coordinate = CLLocationCoordinate2DMake(51.49795, -0.174056);
// Do any additional setup after loading the view.
}
-(void)checkStatus{
CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
if (status==kCLAuthorizationStatusNotDetermined) {
NSLog(@"Not Determined");
}
if (status==kCLAuthorizationStatusDenied) {
NSLog(@"Denied");
}
if (status==kCLAuthorizationStatusRestricted) {
NSLog(@"Restricted");
}
if (status==kCLAuthorizationStatusAuthorizedAlways) {
NSLog(@"Always Allowed");
}
if (status==kCLAuthorizationStatusAuthorizedWhenInUse) {
NSLog(@"NWhen In Use Allowed");
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)viewWillAppear:(BOOL)animated{
}
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 800, 800);
[self.mapKit setRegion:[self.mapKit regionThatFits:region] animated:YES];
}
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(@"didFailWithError: %@", error);
UIAlertView *errorAlert = [[UIAlertView alloc]
initWithTitle:@"Error" message:@"Failed to Get Your Location" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[errorAlert show];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSLog(@"didUpdateToLocation: %@", newLocation);
CLLocation *currentLocation = newLocation;
if (currentLocation != nil) {
NSLog(@"%@",[NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude]);
NSLog(@"%@",[NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude]);
}
}
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
// If it's the user location, just return nil.
if ([annotation isKindOfClass:[MKUserLocation class]])
return nil;
// Handle any custom annotations.
if ([annotation isKindOfClass:[MKPointAnnotation class]])
{
// Try to dequeue an existing pin view first.
MKAnnotationView *pinView = (MKAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:@"CustomPinAnnotationView"];
if (!pinView)
{
// If an existing pin view was not available, create one.
pinView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"CustomPinAnnotationView"];
pinView.canShowCallout = YES;
pinView.image = [UIImage imageNamed:@"ic_map"];
pinView.calloutOffset = CGPointMake(0, 32);
UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
pinView.rightCalloutAccessoryView = rightButton;
} else {
pinView.annotation = annotation;
}
return pinView;
}
return nil;
}
-(void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control {
id <MKAnnotation> annotation = [view annotation];
if ([annotation isKindOfClass:[MKPointAnnotation class]])
{
NSLog(@"Clicked Pizza Shop");
}
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Disclosure Pressed" message:@"Click Cancel to Go Back" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
[alertView show];
}
当点击 Annotation pin 时委托方法将调用
-(void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view
{
NSLog(@"Latitude: %f", view.annotation.coordinate.latitude);
NSLog(@"Longitude: %f", view.annotation.coordinate.longitude);
self.annotationViewCoordinate = view.annotation.coordinate;
[self GetDirections:view.annotation.coordinate];
}
绘制路径
- (void)GetDirections:(CLLocationCoordinate2D)locationCoordinate
{
MKPlacemark *aPlcSource = [[MKPlacemark alloc] initWithCoordinate:self.mapView.userLocation.coordinate addressDictionary:[NSDictionary dictionaryWithObjectsAndKeys:@"",@"", nil]];
MKPlacemark *aPlcDest = [[MKPlacemark alloc] initWithCoordinate:locationCoordinate addressDictionary:[NSDictionary dictionaryWithObjectsAndKeys:@"",@"", nil]];
MKMapItem *mpItemSource = [[MKMapItem alloc] initWithPlacemark:aPlcSource];
[mpItemSource setName:@"Source"];
MKMapItem *mpItemDest = [[MKMapItem alloc] initWithPlacemark:aPlcDest];
[mpItemDest setName:@"Dest"];
MKDirectionsRequest *aDirectReq = [[MKDirectionsRequest alloc] init];
[aDirectReq setSource:mpItemSource];
[aDirectReq setDestination:mpItemDest];
[aDirectReq setTransportType:MKDirectionsTransportTypeAutomobile];
MKDirections *aDirections = [[MKDirections alloc] initWithRequest:aDirectReq];
[aDirections calculateDirectionsWithCompletionHandler:^(MKDirectionsResponse *response, NSError *error) {
if (error) {
NSLog(@"Error :: %@",error);
}
else{
NSArray *aArrRoutes = [response routes];
NSLog(@"Routes :: %@",aArrRoutes);
[self.mapView removeOverlays:self.mapView.overlays];
[aArrRoutes enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
MKRoute *aRoute = obj;
[self.mapView addOverlay:aRoute.polyline];
NSLog(@"Route Name : %@",aRoute.name);
NSLog(@"Total Distance (in Meters) :%f",aRoute.distance);
NSArray *aArrSteps = [aRoute steps];
NSLog(@"Total Steps : %lu",(unsigned long)[aArrSteps count]);
[aArrSteps enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSLog(@"Rout Instruction : %@",[obj instructions]);
NSLog(@"Rout Distance : %f",[obj distance]);
}];
}];
}
}];
}
当用户位置移动时 你可以调用方法
- (void)GetDirections:(CLLocationCoordinate2D)locationCoordinate
来自方法
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
[self GetDirections:self.annotationViewCoordinate];
}