提问者:小点点

如何使用MapBox创建具有特定国家(包括其州)图表数据的可点击地图?


我想制作一张印度地图图表,上面有印度各邦的相关数据,具体如下:

我已经探索了一个Mapbox,并完成了这篇关于编辑地图样式的教程,并在各种工具和应用程序中使用它,如下面的代码片段所示。 但我不知道如何显示单个国家及其州,并将数据与这些州绑定。

var mapView = MGLMapView()
mapView.styleURL = URL(string: "mapbox://styles/davidchopin/cjtz90km70tkk1fo6oxifkd67")

此外,我想使状态是可点击的,这样,如果用户点击特定的状态,它的相关数据将弹出。


共1个答案

匿名用户

在mapbox SDK中,你可以选择一个图层中的特征

您需要在地图视图中添加轻点手势,

 var mapView: MGLMapView!
 let layerIdentifier = "state-layer"

override func viewDidLoad() {
super.viewDidLoad() 

     mapView = MGLMapView(frame: view.bounds)
mapView.delegate = self
mapView.setCenter(CLLocationCoordinate2D(latitude: 16.5440447, longitude: 64.3123835), animated: false)
mapView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
view.addSubview(mapView)

// Add a single tap gesture recognizer. This gesture requires the built-in MGLMapView tap gestures (such as those for zoom and annotation selection) to fail.
let singleTap = UITapGestureRecognizer(target: self, action: #selector(handleMapTap(sender:)))
for recognizer in mapView.gestureRecognizers! where recognizer is UITapGestureRecognizer {
singleTap.require(toFail: recognizer)
}
mapView.addGestureRecognizer(singleTap)
}

并处理该操作,如

   @objc @IBAction func handleMapTap(sender: UITapGestureRecognizer) {
// Get the CGPoint where the user tapped.
let spot = sender.location(in: mapView)

// Access the features at that point within the state layer.
let features = mapView.visibleFeatures(at: spot, styleLayerIdentifiers: Set([layerIdentifier]))

// Get the name of the selected state.
if let feature = features.first, let state = feature.attribute(forKey: "name") as? String {
 print("State Name == \(state)")
} else {
changeOpacity(name: "")
}
}