快速删除地图叠加层 [英] swift remove map overlays

查看:129
本文介绍了快速删除地图叠加层的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从地图上删除叠加层.

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.overlaysAnyObject数组的类型. var overlays: [AnyObject]! { get }.

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

所以最初我写了

var removeOverlays = self.mapView.overlays

它在运行时在此行上引发EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)异常.

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

所以我确实对[AnyObject]进行类型转换,但我不知道它是否正确,但是在运行时它仍然给我同样的异常.

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.

我为Objective C代码所做的是:

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];
}

我试图在Swift中创建类似的方法.但这会引发一个异常,就像我上面解释的那样.

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

推荐答案

我刚刚做到了:

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

,它似乎有效.为什么将叠加层定义为静态变量?

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

这是我们能够使用全局包含功能搜索快速数组并检查要查找的元素是否存在于数组内的方法.在这种情况下,我们正在数组内搜索CLLocationCoordinate2D.

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 {

}

这篇关于快速删除地图叠加层的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆