如果更改分段控件,则快速映射更改点



我正在尝试使用Mapbox。

我在地图上创建了一个点并从文件中显示

我希望在更改SegmentedControl时,相应地更改item.type并获得正确的数据

例如,如果按 0 大小写 ->则使 0 == item.type

我创建自定义点

func addItemsToMap(features: [MGLPointFeature]) {
guard let style = mapView.style else { return }
let source = MGLShapeSource(identifier: "mapPoints", features: features, options: nil)
style.addSource(source)
let colors = [
"black": MGLStyleValue(rawValue: UIColor.black)
]
let circles = MGLCircleStyleLayer(identifier: "mapPoints-circles", source: source)
circles.circleColor = MGLSourceStyleFunction(interpolationMode: .identity,
stops: colors,
attributeName: "color",
options: nil)
circles.circleRadius = MGLStyleValue(interpolationMode: .exponential,
cameraStops: [2: MGLStyleValue(rawValue: 5),
7: MGLStyleValue(rawValue: 8)],
options: nil)
circles.circleStrokeWidth = MGLStyleValue(rawValue: 2)
circles.circleStrokeColor = MGLStyleValue(rawValue: UIColor.white)
style.addLayer(circles)
}

将数据放入地图框

func test(number: Int) {
guard let documentsDirectoryUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
let urlBar = documentsDirectoryUrl.appendingPathComponent("Persons.json")
do {
let jsonData = try Data(contentsOf: urlBar)
//Переводим их в модель
let result = try JSONDecoder().decode(CollectionTest.self, from: jsonData)
let coll: CollectionTest = result
let features = parseJSONItems(collection: coll, number: number)
addItemsToMap(features: features)
print(features)
} catch { print("Error while parsing: (error)") }
}

从文件中获取数据

func parseJSONItems(collection: CollectionTest, number: Int) -> [MGLPointFeature] {
var features = [MGLPointFeature]()
for item in collection.prices {
if item.type == number {
...get data to annotation and location
let feature = MGLPointFeature()
feature.coordinate = coordinate
feature.title = "(name)"
feature.attributes = [
"color" : color,
"name" : "(name)"
]
features.append(feature)
}
}
}}}
}
return features
}

我需要将number0更改为4,因为在数据中,我的类型从0更改为4,并且点需要从0更改 - 如果更改SegmentedControl4

在我有SegmentedControl

@objc func change(sender: UISegmentedControl) {
switch sender.selectedSegmentIndex {
case 0:
test(number: 0)
case 1:
test(number: 1)
case 2:
ttest(number: 2)
case 3:
test(number: 3)
case 4:
test(number: 4)
default:
test(number: 2)
}
}

在视图中DidLoad:

override func viewDidLoad() {
super.viewDidLoad()
styleToggle.addTarget(self, action: #selector(change(sender:)), for: .valueChanged)
test(number: 2)
}

当应用程序运行时 - 运行良好并显示所有数据 == 类型 2

但是当我将SegmentedControl中的按钮更改为case 0或其他按钮时 - 我崩溃并在控制台打印中

由于未捕获的异常"MGLRedundant源标识符异常
"而终止应用,原因:"源映射点已存在">

我做错了什么?如何解决这个问题?

您似乎正在尝试向地图添加已存在的源。为了避免此消息,您需要:

  1. 在将源添加到样式之前,请检查源是否存在。在您的用例中,可以将您的来源命名为mapPoints-circles-(number).如果源已存在,请重用它。

  2. 将源添加到映射一次(最好在初始-mapView:didFinishLoadingStyle:内(。要从该图层创建新图层,您可以从地图样式访问源。

如果这些点来自标识符my-source的源,您可以尝试:

guard let source = style.source(withIdentifier: "my-source") else { return }

单击线段时,删除地图中已存在的所有标记 然后添加新标记

您可以使用map.removeLayer(marker(来删除标记(ILayer对象(。

最新更新