メインコンテンツまでスキップ

Show and hide a layer

A newer version of the Maps SDK is available

This page uses v6.4.1 of the Mapbox Maps SDK. A newer version of the SDK is available. Learn about the latest version, v11.7.0, in the Maps SDK documentation.

Related example: custom raster source.

ViewController
import Mapbox

class ViewController: UIViewController, MGLMapViewDelegate {
var mapView: MGLMapView!
var contoursLayer: MGLStyleLayer?

override func viewDidLoad() {
super.viewDidLoad()

mapView = MGLMapView(frame: view.bounds)
mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]

mapView.setCenter(CLLocationCoordinate2D(latitude: 37.745395, longitude: -119.594421), zoomLevel: 11, animated: false)
view.addSubview(mapView)

addToggleButton()

mapView.delegate = self
}

// Wait until the style is loaded before modifying the map style
func mapView(_ mapView: MGLMapView, didFinishLoading style: MGLStyle) {
addLayer(to: style)
}

func addLayer(to style: MGLStyle) {
let source = MGLVectorTileSource(identifier: "contours", configurationURL: NSURL(string: "mapbox://mapbox.mapbox-terrain-v2")! as URL)

let layer = MGLLineStyleLayer(identifier: "contours", source: source)
layer.sourceLayerIdentifier = "contour"
layer.lineJoin = NSExpression(forConstantValue: "round")
layer.lineCap = NSExpression(forConstantValue: "round")
layer.lineColor = NSExpression(forConstantValue: UIColor.brown)
layer.lineWidth = NSExpression(forConstantValue: 1.0)

style.addSource(source)
if let water = style.layer(withIdentifier: "water") {
// You can insert a layer below an existing style layer
style.insertLayer(layer, below: water)
} else {
// or you can simply add it above all layers
style.addLayer(layer)
}

self.contoursLayer = layer

showContours()
}

@objc func toggleLayer(sender: UIButton) {
sender.isSelected = !sender.isSelected
if sender.isSelected {
showContours()
} else {
hideContours()
}
}

func showContours() {
self.contoursLayer?.isVisible = true
}

func hideContours() {
self.contoursLayer?.isVisible = false
}

func addToggleButton() {
let button = UIButton(type: .system)
button.setTitle("Toggle Contours", for: .normal)
button.isSelected = true
button.sizeToFit()
button.center.x = self.view.center.x
button.frame = CGRect(origin: CGPoint(x: button.frame.origin.x, y: self.view.frame.size.height - button.frame.size.height - 5), size: button.frame.size)
button.addTarget(self, action: #selector(toggleLayer(sender:)), for: .touchUpInside)
self.view.addSubview(button)

if #available(iOS 11.0, *) {
let safeArea = view.safeAreaLayoutGuide
button.translatesAutoresizingMaskIntoConstraints = false
let constraints = [
button.bottomAnchor.constraint(equalTo: safeArea.bottomAnchor, constant: -5),
button.centerXAnchor.constraint(equalTo: safeArea.centerXAnchor)
]

NSLayoutConstraint.activate(constraints)
} else {
button.autoresizingMask = [.flexibleTopMargin, .flexibleLeftMargin, .flexibleRightMargin]
}
}
}