在MapView上绘制MKPolyline显示两个位置之间的直线

时间:2016-07-01 11:33:12

标签: ios iphone mkannotation apple-maps mkpolyline

如何获取谷歌地图等位置,以显示位置之间的确切路径。因为它显示直线直线,它不包含两个地方之间的任何路径,也没有显示它通过的位置。 我使用了以下代码:

CLLocationCoordinate2D coordinateArray[2];
    coordinateArray[0] = CLLocationCoordinate2DMake(51.5074, 0.1278);
    coordinateArray[1] = CLLocationCoordinate2DMake(48.8566, 2.3522);


    self.routeLine = [MKPolyline polylineWithCoordinates:coordinateArray count:2];
    [self.mapView setVisibleMapRect:[self.routeLine boundingMapRect]]; //If you want the route to be visible

    [self.mapView addOverlay:self.routeLine];

用于连接这两个路径的代码已经实现。

-(MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id<MKOverlay>)overlay
{
    if(overlay == self.routeLine)
    {
        if(nil == self.routeLineView)
        {
            self.routeLineView = [[MKPolylineView alloc] initWithPolyline:self.routeLine];
            self.routeLineView.fillColor = [UIColor redColor];
            self.routeLineView.strokeColor = [UIColor redColor];
            self.routeLineView.lineWidth = 5;

        }

        return self.routeLineView;
    }

    return nil;
}

2 个答案:

答案 0 :(得分:0)

试一下我的代码:

- (void)drawRouteFromLocation:(LocationPin *)source toLocation:(LocationPin *)destination

{
    [self removeCurrentRouteDrawing];

    MKPlacemark *sourcePlaceMark = [[MKPlacemark alloc]initWithCoordinate:source.actualCoordinate addressDictionary:nil];
    MKPlacemark *destinationPlaceMark = [[MKPlacemark alloc]initWithCoordinate:destination.actualCoordinate addressDictionary:nil];

    MKDirectionsRequest *request = [[MKDirectionsRequest alloc] init];

    request.source = [[MKMapItem alloc] initWithPlacemark:sourcePlaceMark];
    request.destination = [[MKMapItem alloc] initWithPlacemark:destinationPlaceMark];
    request.requestsAlternateRoutes = NO;
    MKDirections *directions = [[MKDirections alloc] initWithRequest:request];

    [directions calculateDirectionsWithCompletionHandler:
     ^(MKDirectionsResponse *response, NSError *error) {
         if (error)
         {
             // Handle Error
         }
         else
         {
             [self showRoute:response];
         }
     }];
}

-(void)showRoute:(MKDirectionsResponse *)response
{
    for (MKRoute *route in response.routes)
    {
        [self.mkMapView addOverlay:route.polyline level:MKOverlayLevelAboveRoads];
//        for (MKRouteStep *step in route.steps)
//        {
//            DEBUG_LOG(@"%@", step.instructions);
//        }

    }
}

#pragma mark - MKMapViewDelegate
- (void)mapView:(MKMapView *)mapView regionWillChangeAnimated:(BOOL)animated
{
//    DEBUG_LOG(@"region Will Change");

    if ([self.delegate respondsToSelector:@selector(mapView:regionWillChangeAnimated:)])
    {
        [self.delegate mapView:mapView regionWillChangeAnimated:animated];
    }

}

- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
//    DEBUG_LOG(@"region Did Change");

    if ([self.delegate respondsToSelector:@selector(mapView:regionDidChangeAnimated:)])
    {
        [self.delegate mapView:mapView regionDidChangeAnimated:animated];
    }

}

- (void)mapViewDidFinishLoadingMap:(MKMapView *)mapView
{
    DEBUG_LOG(@"mapView Did Finish Loading Map");
    self.mapInitialized = YES;

    if ([self.delegate respondsToSelector:@selector(mapViewDidFinishLoadingMap:)])
    {
        [self.delegate mapViewDidFinishLoadingMap:mapView];
    }
}

//- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay
//{
//    if ([overlay isKindOfClass: [MKPolyline class]])
//    {
//        // This is for a dummy overlay to work around a problem with overlays
//        // not getting removed by the map view even though we asked for it to
//        // be removed.
//        MKOverlayView * dummyView = [[MKOverlayView alloc] init];
//        dummyView.alpha = 0.0;
//        return dummyView;
//    }
//    else
//    {
//        return nil;
//    }
//}

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
    if ([self.delegate respondsToSelector:@selector(mapView:viewForAnnotation:)])
    {
        return [self.delegate mapView:mapView viewForAnnotation:annotation];
    }

    return nil;
}

- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id < MKOverlay >)overlay
{
    if ([overlay isKindOfClass:[MKPolyline class]])
    {
        MKPolylineRenderer *renderer = [[ MKPolylineRenderer alloc]initWithOverlay:overlay];
        renderer.lineWidth = 10;
        renderer.strokeColor = [UIColor colorWithRed:0.0 green:122.0/255.0 blue:1.0 alpha:1.0];
        [self _zoomToPolyLine:self.mkMapView polyLine:overlay animated:YES];
        return renderer;
    }
    else
    {
        return nil;
    }
}


#pragma mark - Utils

-(void)_zoomToPolyLine:(MKMapView*)map polyLine:(MKPolyline*)polyLine animated:(BOOL)animated
{
//    MKPolygon* polygon =
//    [MKPolygon polygonWithPoints:polyLine.points count:polyLine.pointCount];
//    
//    [self.mkMapView setRegion:MKCoordinateRegionForMapRect([polygon boundingMapRect])
//          animated:animated];

    [map setVisibleMapRect:[polyLine boundingMapRect] edgePadding:UIEdgeInsetsMake(35.0, 35.0, 35.0, 35.0) animated:animated];
}

- (void)removeCurrentRouteDrawing
{
    if (self.mkMapView.overlays.count)
    {
        [self.mkMapView removeOverlays:self.mkMapView.overlays];

    }
}

答案 1 :(得分:0)

ios中两个坐标之间的地图上的方向

- (MKPolyline *)polylineWithEncodedString:(NSString *)encodedString
{
    const char *bytes = [encodedString UTF8String];
    NSUInteger length = [encodedString lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
    NSUInteger idx = 0;
    NSUInteger count = length / 4;
    CLLocationCoordinate2D *coords = calloc(count, sizeof(CLLocationCoordinate2D));
    NSUInteger coordIdx = 0;
    float latitude = 0;
    float longitude = 0;
    while (idx < length) {
        char byte = 0;
        int res = 0;
        char shift = 0;
        do {
            byte = bytes[idx++] - 63;
            res |= (byte & 0x1F) << shift;
            shift += 5;
        } while (byte >= 0x20);

        float deltaLat = ((res & 1) ? ~(res >> 1) : (res >> 1));
        latitude += deltaLat;

        shift = 0;
        res = 0;

        do {
            byte = bytes[idx++] - 0x3F;
            res |= (byte & 0x1F) << shift;
            shift += 5;
        } while (byte >= 0x20);

        float deltaLon = ((res & 1) ? ~(res >> 1) : (res >> 1));
        longitude += deltaLon;

        float finalLat = latitude * 1E-5;
        float finalLon = longitude * 1E-5;

        CLLocationCoordinate2D coord = CLLocationCoordinate2DMake(finalLat, finalLon);
        coords[coordIdx++] = coord;

        if (coordIdx == count) {
            NSUInteger newCount = count + 10;
            coords = realloc(coords, newCount * sizeof(CLLocationCoordinate2D));
            count = newCount;
        }
    }

    MKPolyline *polyline = [MKPolyline polylineWithCoordinates:coords count:coordIdx];
    free(coords);

    [self.mapview setVisibleMapRect:[polyline boundingMapRect]];
    [self.mapview addOverlay:polyline];
    return polyline;
}

- (MKPolylineRenderer *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay
{

    // create a polylineView using polyline overlay object
    MKPolylineRenderer *polylineView = [[MKPolylineRenderer alloc] initWithPolyline:overlay];

    // Custom polylineView
    polylineView.strokeColor =  [UIColor blueColor];
    polylineView.lineWidth = 1.0;
    polylineView.alpha = 0.9;

    return polylineView;

}


- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
    self.mapview.centerCoordinate = userLocation.location.coordinate;

    NSString *userCordinate=[NSString stringWithFormat:@"%f,%f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude];


    NSString *apikey = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/directions/json?origin=%@&destination=%@",cordinate1,cordinate2];          // your cordinates replace by cordinate1 & cordinate2

    NSURL *url = [NSURL URLWithString:apikey];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLResponse *response;
    NSError *error;
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];

    if(!error)
    {
        NSData *data = [responseString dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

        NSArray *routesArray = [jsonResponse objectForKey:@"routes"];
        //        NSLog(@"route array %@",routesArray);

        if ([routesArray count] > 0)
        {
            NSDictionary *routeDict = [routesArray objectAtIndex:0];
            NSDictionary *routeOverviewPolyline = [routeDict objectForKey:@"overview_polyline"];
            NSString *points = [routeOverviewPolyline objectForKey:@"points"];
            MKPolyline *line = [self polylineWithEncodedString:points];
            [mapView addOverlay:line];
        }
    }

}