Ios 地图路线视图显示不正确

Ios 地图路线视图显示不正确,ios,objective-c,mapkit,Ios,Objective C,Mapkit,我实现了一个map,它工作得很好。但当我尝试放大地图时,我发现了这个问题: 这是我的密码: -(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation { MKAnnotationView* annotationView = [[MKAnnotationView alloc] initWithAnnotation:annotation reu

我实现了一个map,它工作得很好。但当我尝试放大地图时,我发现了这个问题:

这是我的密码:

-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
    MKAnnotationView* annotationView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"LocationPin"];
    if ([annotation isEqual:self.startLocation]) {
        annotationView.image = [UIImage imageNamed:@"startPin.png"];
        return annotationView;
    } else if ([annotation isEqual:self.endLocation]){
        annotationView.image = [UIImage imageNamed:@"endPin.png"];
        return annotationView;
    }

    return nil;
}

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

}
-(MKAnnotationView*)地图视图:(MKMapView*)地图视图注释:(id)注释
{
MKAnnotationView*annotationView=[[MKAnnotationView alloc]initWithAnnotation:annotation重用标识符:@“LocationPin”];
if([annotation isEqual:self.startLocation]){
annotationView.image=[UIImage ImageName:@“startPin.png”];
返回注释视图;
}else if([annotation isEqual:self.endLocation]){
annotationView.image=[UIImage ImageName:@“endPin.png”];
返回注释视图;
}
返回零;
}
-(MKOverlayRenderer*)地图视图:(MKMapView*)地图视图渲染器ForOverlay:(id)overlay{
@自动释放池{
if([overlay iskindof类:[MKPolyline类]]){
MKPolylineRenderer*渲染器=[[MKPolylineRenderer alloc]initWithOverlay:overlay];
[颜色:kColor_洋红];
[渲染器设置线宽:4.0];
返回渲染器;
}
返回零;
}
}

这可能与缩放时重新绘制多段线有关。检查这个答案

-(void)LoadMapRoute:(NSString*)源地址和目标地址:(NSString*)目标地址
{
NSString*strUrl;
strUrl=[NSString stringWithFormat:@”http://maps.googleapis.com/maps/api/directions/json?origin=%@&目的地=%@&传感器=true“,源地址,目的地地址];
NSLog(@“strUrl===%@),strUrl);
strUrl=[strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSData*data=[NSData data WITHCONTENTSOFURL:[NSURL URLWithString:strUrl]];
n错误*错误;
如果(数据){
NSDictionary*json=[NSJSONSerialization
JSONObjectWithData:data//1
选项:针织品
错误:&错误];
NSArray*arrRouts=[json objectForKey:@“routes”];
if([arrRouts iskindof类:[NSArray类]]&&arrRouts.count==0){
[自我展示提醒:@“未找到方向”];
返回;
}
NSArray*arrDistance=[[json valueForKeyPath:@“routes.legs.steps.distance.text”]objectAtIndex:0]objectAtIndex:0];
NSString*totalDuration=[[json valueForKeyPath:@“routes.legs.duration.text”]objectAtIndex:0]objectAtIndex:0];
NSString*totalDistance=[[json valueForKeyPath:@“routes.legs.distance.text”]objectAtIndex:0]objectAtIndex:0];
NSArray*arrDescription=[[json valueForKeyPath:@“routes.legs.steps.html_指令”]objectAtIndex:0]objectAtIndex:0];
dictRouteInfo=[NSDictionary Dictionary Dictionary WithObjectsSandKey:totalDistance、@“totalDistance”、totalDuration、@“totalDuration”、arrDistance、@“distance”、arrDescription、@“description”、nil];
[self.btnDirection setEnabled:否];
如果(dictRouteInfo){
[self.btnDirection setEnabled:是];
}
NSArray*arrpolyline=[[[json valueForKeyPath:@“routes.legs.steps.polyline.points”]objectAtIndex:0]objectAtIndex:0];//2
double srcLat=[[[json valueForKeyPath:@“routes.legs.start_location.lat”]objectAtIndex:0]objectAtIndex:0]doubleValue];
double srcLong=[[[json valueForKeyPath:@“routes.legs.start_location.lng”]objectAtIndex:0]objectAtIndex:0]doubleValue];
double destrat=[[[json valueForKeyPath:@“routes.legs.end_location.lat”]objectAtIndex:0]objectAtIndex:0]doubleValue];
double destLong=[[[json valueForKeyPath:@“routes.legs.end_location.lng”]objectAtIndex:0]objectAtIndex:0]doubleValue];
CLLocationCoordinate2D sourceCordinate=CLLocationCoordinate2DMake(srcLat,srcLong);
CLLocationCoordinate2D destCordinate=CLLocationCoordinate2DMake(destLat,destLong);
[self-AddAnnotationsCandDestination:sourceCordinate:destCordinate and-Address:SourceAddress and DestinationAddress:DestinationAdds];
//NSArray*步骤=[[aary objectAtIndex:0]valueForKey:@“步骤”];
//将管路更换为此可能会起作用
NSMutableArray*polyLinesArray=[[NSMutableArray alloc]initWithCapacity:0];
对于(int i=0;i<[多段线计数];i++)
{
NSString*encodedPoints=[arrpolyline objectAtIndex:i];
MKPolyline*route=[带encodedString的自多段线:encodedPoints];
[多段线阵列添加对象:路由];
}
[self.mapShow addOverlays:polyLinesArray];
self.mapShow.delegate=self;
[self zoomtofitmanotations:self.mapShow];
}否则{
[self.btnDirection setEnabled:否];
[自我展示提醒:@“未找到方向”];
}
}
#杂注标记-在源和目标上添加注释
-(void)addAnnotationSrcAndDestination:(CLLocationCoordinate2D)srcCord:(CLLocationCoordinate2D)destCord和adds:(NSString*)源地址和目的地址:(NSString*)目的地址adds
{
MKPointAnnotation*sourceAnnotation=[[MKPointAnnotation alloc]init];
MKPointAnnotation*destAnnotation=[[MKPointAnnotation alloc]init];
sourceAnnotation.coordinate=srcCord;
destAnnotation.coordinate=destCord;
sourceAnnotation.title=源地址;
destAnnotation.title=DestinationAdds;
[self.mapShow addAnnotation:sourceAnnotation];
[self.mapShow addAnnotation:destAnnotation];
}
#pragma标记-解码地图多段线
-(MKPolyline*)带encodedString的polyline:(NSString*)encodedString{
常量字符*字节=[encodedString UTF8String];
NSUTInteger长度=[encodedString LengthofBytes使用编码:NSUTF8StringEncoding];
整数idx=0;
NSU整数计数=长度/4;
CLLocationCoordinate2D*coords=calloc(count,sizeof(CLLocationCoordinate2D));
NSU整数坐标=0;
浮动纬度=0;
浮动经度=0;
while(idx>1):(res>>1));
纬度+=三角洲;
移位=0;
res=0;
做{
字节=字节[idx++]-0x3F;
res |=(字节&0x1F)=0x20);
浮点数=((res&1)~(res>>1):(res>>1));
朗
-(void)LoadMapRoute:(NSString*)SourceAddress andDestinationAddress:(NSString*)DestinationAdds
{
NSString *strUrl;
strUrl= [NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/directions/json?origin=%@&destination=%@&sensor=true",SourceAddress,DestinationAdds];
NSLog(@"strUrl=====%@",strUrl);
strUrl=[strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSData *data =[NSData dataWithContentsOfURL:[NSURL URLWithString:strUrl]];
NSError* error;
if (data) {
    NSDictionary* json = [NSJSONSerialization
                          JSONObjectWithData:data //1
                          options:kNilOptions
                          error:&error];
    NSArray *arrRouts=[json objectForKey:@"routes"];
    if ([arrRouts isKindOfClass:[NSArray class]]&&arrRouts.count==0) {
        [self ShowAlert:@"didn't find direction"];
        return;
    }
    NSArray *arrDistance =[[[json valueForKeyPath:@"routes.legs.steps.distance.text"] objectAtIndex:0]objectAtIndex:0];
    NSString *totalDuration = [[[json valueForKeyPath:@"routes.legs.duration.text"] objectAtIndex:0]objectAtIndex:0];
    NSString *totalDistance = [[[json valueForKeyPath:@"routes.legs.distance.text"] objectAtIndex:0]objectAtIndex:0];
    NSArray *arrDescription =[[[json valueForKeyPath:@"routes.legs.steps.html_instructions"] objectAtIndex:0] objectAtIndex:0];
    dictRouteInfo=[NSDictionary dictionaryWithObjectsAndKeys:totalDistance,@"totalDistance",totalDuration,@"totalDuration",arrDistance ,@"distance",arrDescription,@"description", nil];
    [self.btnDirection setEnabled:NO];
    if (dictRouteInfo) {
        [self.btnDirection setEnabled:YES];
    }
    NSArray* arrpolyline = [[[json valueForKeyPath:@"routes.legs.steps.polyline.points"] objectAtIndex:0] objectAtIndex:0]; //2
    double srcLat=[[[[json valueForKeyPath:@"routes.legs.start_location.lat"] objectAtIndex:0] objectAtIndex:0] doubleValue];
    double srcLong=[[[[json valueForKeyPath:@"routes.legs.start_location.lng"] objectAtIndex:0] objectAtIndex:0] doubleValue];
    double destLat=[[[[json valueForKeyPath:@"routes.legs.end_location.lat"] objectAtIndex:0] objectAtIndex:0] doubleValue];
    double destLong=[[[[json valueForKeyPath:@"routes.legs.end_location.lng"] objectAtIndex:0] objectAtIndex:0] doubleValue];
    CLLocationCoordinate2D sourceCordinate = CLLocationCoordinate2DMake(srcLat, srcLong);
    CLLocationCoordinate2D destCordinate = CLLocationCoordinate2DMake(destLat, destLong);

    [self addAnnotationSrcAndDestination:sourceCordinate :destCordinate andAdds:SourceAddress andDestinationAddress:DestinationAdds];
    //    NSArray *steps=[[aary objectAtIndex:0]valueForKey:@"steps"];

    //    replace lines with this may work

    NSMutableArray *polyLinesArray =[[NSMutableArray alloc]initWithCapacity:0];

    for (int i = 0; i < [arrpolyline count]; i++)
    {
        NSString* encodedPoints = [arrpolyline objectAtIndex:i] ;
        MKPolyline *route = [self polylineWithEncodedString:encodedPoints];
        [polyLinesArray addObject:route];
    }
    [self.mapShow addOverlays:polyLinesArray];
    self.mapShow.delegate = self;
    [self zoomToFitMapAnnotations:self.mapShow];
}else{
    [self.btnDirection setEnabled:NO];
    [self ShowAlert:@"didn't find direction"];
}
}
#pragma mark - add annotation on source and destination

-(void)addAnnotationSrcAndDestination :(CLLocationCoordinate2D )srcCord :(CLLocationCoordinate2D)destCord andAdds:(NSString*)SourceAddress andDestinationAddress:(NSString*)DestinationAdds
{
MKPointAnnotation *sourceAnnotation = [[MKPointAnnotation alloc]init];
MKPointAnnotation *destAnnotation = [[MKPointAnnotation alloc]init];
sourceAnnotation.coordinate=srcCord;
destAnnotation.coordinate=destCord;
sourceAnnotation.title=SourceAddress;
destAnnotation.title=DestinationAdds;
[self.mapShow addAnnotation:sourceAnnotation];
[self.mapShow addAnnotation:destAnnotation];
}

#pragma mark - decode map polyline

- (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);

return polyline;
}
#pragma mark - map overlay
-(MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay
{
MKPolylineRenderer *renderer = [[MKPolylineRenderer alloc] initWithOverlay:overlay];
renderer.strokeColor = [UIColor colorWithRed:155.0/255.0 green:89.0/255.0 blue:182.0/255.0 alpha:1.0];
renderer.lineWidth = 5.0;
return renderer;
}