Подтвердить что ты не робот

Есть ли способ получить маршруты в mkmapview, используя встроенный API-интерфейс Apple?

Я знаю, что карты google, как известно, являются лучшими картами, но я не хочу загружать кучу дополнительных библиотек и все такое. Я бы предпочел сделать что-то быстро и просто, чтобы быстро добраться от точки А до Б и сделать с ней. Есть ли способ сделать это со встроенными функциями/библиотеками? Может ли кто-нибудь указать мне в правильном направлении?

ИЗМЕНИТЬ

Я не пытаюсь получить поворот в повороте или что-то в моем случае, я просто хочу нарисовать линию от начала до конца. возможно, дать варианты о том, какие маршруты нужно предпринять. Есть ли способ сделать это или нет?

4b9b3361

Ответ 1

В iOS 7 вы можете получать и отображать направления с помощью MKDirectionsRequest.

Вот пример кода для отображения направлений от текущего местоположения к другому элементу карты:

MKDirectionsRequest *request = [[MKDirectionsRequest alloc] init];
[request setSource:[MKMapItem mapItemForCurrentLocation]];
[request setDestination:myMapItem];
[request setTransportType:MKDirectionsTransportTypeAny]; // This can be limited to automobile and walking directions.
[request setRequestsAlternateRoutes:YES]; // Gives you several route options.
MKDirections *directions = [[MKDirections alloc] initWithRequest:request];
[directions calculateDirectionsWithCompletionHandler:^(MKDirectionsResponse *response, NSError *error) {
    if (!error) {
        for (MKRoute *route in [response routes]) {
            [myMapView addOverlay:[route polyline] level:MKOverlayLevelAboveRoads]; // Draws the route above roads, but below labels.
            // You can also get turn-by-turn steps, distance, advisory notices, ETA, etc by accessing various route properties.
        }
    }
}];

Если вы новичок в iOS 7, вам нужно реализовать метод mapView:rendererForOverlay: для отображения любого наложения. Что-то вроде:

- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay
{
    if ([overlay isKindOfClass:[MKPolyline class]]) {
        MKPolylineRenderer *renderer = [[MKPolylineRenderer alloc] initWithOverlay:overlay];
        [renderer setStrokeColor:[UIColor blueColor]];
        [renderer setLineWidth:5.0];
        return renderer;
    }
    return nil;
}

Ответ 2

Быстрая версия

        let request = MKDirectionsRequest();
        request.source = MKMapItem.mapItemForCurrentLocation();
        let locationPlacemark = MKPlacemark(coordinate: CLLocationCoordinate2DMake(13.724362, 100.515342), addressDictionary: nil);
        request.destination = MKMapItem(placemark: locationPlacemark);
        request.transportType = MKDirectionsTransportType.Any;
        request.requestsAlternateRoutes = true;
        let directions = MKDirections(request: request);

        directions.calculateDirectionsWithCompletionHandler ({
            (response: MKDirectionsResponse?, error: NSError?) in
            print(response?.description)
            print(error?.description)
            guard let response = response else {
                //handle the error here
                return;
            }
            self.myRoute = response.routes[0]
            self.mkMapView.addOverlay(self.myRoute!.polyline)
        });

и его делегат

        func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer {
        let myLineRenderer = MKPolylineRenderer(polyline: (self.myRoute?.polyline)!)
        myLineRenderer.strokeColor = UIColor.redColor()
        myLineRenderer.lineWidth = 3
        return myLineRenderer
        }

Ответ 3

Другая возможность - отправить адрес в приложение Apple Maps. Я просто видел это в профессиональной обстановке, и это был выбранный метод.

Ответ 4

если вы хотите показать диалоговое окно оповещений, когда вы нажали на контакт, сделайте это:

- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view     calloutAccessoryControlTapped:(UIControl *)control {
[mapView deselectAnnotation:view.annotation animated:YES];

    if ([view.annotation isKindOfClass:[PinOfProject class]])
    {
        CLLocationCoordinate2D coordinate = [view.annotation coordinate];
        MKPlacemark *placemark = [[MKPlacemark alloc] initWithCoordinate:coordinate addressDictionary:nil];
        MKMapItem *mapitem = [[MKMapItem alloc] initWithPlacemark:placemark];
        self.mapItem = mapitem;

        CGPoint pin = [mapView convertCoordinate:view.annotation.coordinate toPointToView:self.view];
        CGRect rec = CGRectMake(pin.x-13, pin.y-14,view.frame.size.width,view.frame.size.height);


        [self showAlertInformationForTrash:rec];

    }
}

-(void)showAlertInformationForTrash:(CGRect)rec{

    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Show Route?" delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:@"Route", @"Cancel", nil];
    actionSheet.tag = 1;
    [actionSheet showFromRect:rec inView:self.view animated:YES];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        [self showRouteToAnnotation];
    }
}

-(void)showRouteToAnnotation{
    MKMapItem *myMapItem = self.mapItem;
    MKDirectionsRequest *request = [[MKDirectionsRequest alloc] init];
    [request setSource:[MKMapItem mapItemForCurrentLocation]];
    [request setDestination:myMapItem];
    [request setTransportType:MKDirectionsTransportTypeAutomobile]; // This can be limited to automobile and walking directions.
    [request setRequestsAlternateRoutes:NO]; // Gives you several route options.
    MKDirections *directions = [[MKDirections alloc] initWithRequest:request];
    [directions calculateDirectionsWithCompletionHandler:^(MKDirectionsResponse *response, NSError *error) {
        if (!error) {
            for (MKRoute *route in [response routes]) {
                [self.mapView addOverlay:[route polyline] level:MKOverlayLevelAboveRoads]; // Draws the route above roads, but below labels.
                for (int i = 0; i < route.steps.count; i++) {
                    MKRouteStep *step = [route.steps objectAtIndex:i];
                    NSString *newStep = step.instructions;
                    NSLog(@"%@", newStep);
                }                                                                       
            }
        }
    }];
}

- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay
{
    if ([overlay isKindOfClass:[MKPolyline class]]) {
        MKPolylineRenderer *renderer = [[MKPolylineRenderer alloc] initWithOverlay:overlay];
        [renderer setStrokeColor:[UIColor blueColor]];
        [renderer setLineWidth:5.0];
        return renderer;
    }
    return nil;
}
  • О, но обратите внимание, что я создаю свойство в моем .h @property (сильный, неатомный) MKMapItem * mapItem;