移动端技术分享

iOS MKMap线路规划

2020-06-09  本文已影响0人  Mr_Atom

高德地图的路线规划内容要丰富一些,还有路况信息等一些东西.但是基础功能,用iOS系统自带的地图就完全可以实现.
核心方法如下:

- (void)fetchPathWithOrigin:(CLLocationCoordinate2D)origin destination:(CLLocationCoordinate2D)destination {
    MKPlacemark *originPlacemark = [[MKPlacemark alloc] initWithCoordinate:origin addressDictionary:nil];
    MKPlacemark *destinationPlaceMark = [[MKPlacemark alloc] initWithCoordinate:destination addressDictionary:nil];
    MKMapItem *originItem = [[MKMapItem alloc] initWithPlacemark:originPlacemark];
    MKMapItem *destinationItem = [[MKMapItem alloc] initWithPlacemark:destinationPlaceMark];
    [self searchPathWithOrigin:originItem destination:destinationItem];
}
- (void)searchPathWithOrigin:(MKMapItem *)origin destination:(MKMapItem *)destination {
    
    MKDirectionsRequest *request = [[MKDirectionsRequest alloc] init];
    request.source = origin;
    request.destination = destination;
    request.requestsAlternateRoutes = true;
    MKDirections *direction = [[MKDirections alloc] initWithRequest:request];
    WS();
    [direction calculateDirectionsWithCompletionHandler:^(MKDirectionsResponse * _Nullable response, NSError * _Nullable error) {
        if (!error) {
            MKRoute *route = response.routes.firstObject;
            weakSelf.polyLine = route.polyline;
            [weakSelf.mapView addOverlay:route.polyline];
            [weakSelf.mapView setNeedsDisplay];
//            weakSelf.mapView showo
            [weakSelf showOverLayWithOrigin:origin.placemark.coordinate destination:destination.placemark.coordinate];
        }
    }];
}
- (void)showOverLayWithOrigin:(CLLocationCoordinate2D)origin destination:(CLLocationCoordinate2D)destination {
    MKCoordinateRegion region;
    const double extraSpace = 1.5;
    region.center.latitude = origin.latitude - (origin.latitude - destination.latitude) / 2;
    region.center.longitude = origin.longitude - (origin.longitude - destination.longitude) / 2;
    region.span.latitudeDelta = fabs(origin.latitude - destination.latitude) * extraSpace;
    region.span.longitudeDelta = fabs(origin.longitude - destination.longitude) * extraSpace;
    [self.mapView setRegion:region animated:true];
}
上一篇下一篇

猜你喜欢

热点阅读