Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
788 views
in Technique[技术] by (71.8m points)

ios - swift remove map overlays

I am trying to remove overlays from map.

func removeMapOverlay() {

    var removeOverlays : [AnyObject]! = self.mapView.overlays
    // Above line throws runtime exception

    self.mapView.removeOverlays(removeOverlays)
}

self.mapView.overlays are type of AnyObject array. var overlays: [AnyObject]! { get }.

So initially I wrote

var removeOverlays = self.mapView.overlays

It throws EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) exception at this line on runtime.

So I did type casting for [AnyObject] I don't know it is correct or not but it still gives me same exception at runtime.

Edit:

What I did for Objective C code was:

- (void) removeMapOverlay {
    [self.mapView removeOverlays:[self.mapView overlays]];

    NSMutableArray *tempArray = [NSMutableArray arrayWithArray:[self.mapView annotations]];
    if ([tempArray containsObject:[MKUserLocation class]]) {
        [tempArray removeObject:[MKUserLocation class]];
    }

    NSArray *annotationArray = [NSArray arrayWithArray:tempArray];
    tempArray = nil;
    [self.mapView removeAnnotations:annotationArray];
}

I tried to create similar method in Swift. But it throws an exception like I explain above.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I've just done this:

let overlays = mapView.overlays
mapView.removeOverlays(overlays)

and it seems to work. Why do you define your overlays as a static variable?

EDIT:

This is what we've done to be able to use the global contains function to search a swift array and check if the element we're looking for exists inside the array or not. In this case we were searching for CLLocationCoordinate2D inside an array.

public func == (lhs: CLLocationCoordinate2D, rhs: CLLocationCoordinate2D) -> Bool {
return lhs.longitude == rhs.longitude && lhs.latitude == rhs.latitude
}

public func == (lhs: MKMapPoint, rhs: MKMapPoint) -> Bool {
    return lhs.x == rhs.x && lhs.y == rhs.y
}

extension CLLocationCoordinate2D: Equatable{

}

//This is needed to be Equatable to use the global contains function
extension MKMapPoint: Equatable {

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...