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

Add a marker symbol to the map

This example demonstrates how to add a single marker symbol to a map using the Mapbox Maps SDK for iOS in a Swift application. The AddOneMarkerSymbolExample class creates a MapView instance with a specified initial camera position and adds it to the view. After loading the map style, a marker annotation is added to the map by defining a custom image for the marker and setting its position and appearance properties. In this case, the marker displays a red pin icon at the given coordinates.

The marker annotation is added by creating an image with the specified identifier, defining a GeoJSONSource with the coordinates for the marker, and creating a SymbolLayer that references the image and sets its display properties. The marker's position uses the latitude and longitude defined in the Constants struct.

iOS Examples App Available

This example code is part of the Maps SDK for iOS Examples App, a working iOS project available on Github. iOS developers are encouraged to run the examples app locally to interact with this example in an emulator and explore other features of the Maps SDK.

See our Run the Maps SDK for iOS Examples App tutorial for step-by-step instructions.

AddOneMarkerSymbolExample
import UIKit
import MapboxMaps

final class ViewController: UIViewController {
private lazy var mapView: MapView = {
let options = MapInitOptions(cameraOptions: CameraOptions(center: Constants.coordinate, zoom: 8))

return MapView(frame: view.bounds, mapInitOptions: options)
}()

override func viewDidLoad() {
super.viewDidLoad()

mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.addSubview(mapView)

mapView.mapboxMap.loadStyle(.standard) { [weak self] error in
guard error == nil else { return }

self?.addMarkerAnnotation()


}
}

private func addMarkerAnnotation() {
try? mapView.mapboxMap.addImage(UIImage(named: "dest-pin")!, id: Constants.RED_ICON_ID)

var source = GeoJSONSource(id: Constants.SOURCE_ID)
source.data = .geometry(Geometry.point(Point(Constants.coordinate)))
try? mapView.mapboxMap.addSource(source)

var layer = SymbolLayer(id: Constants.LAYER_ID, source: Constants.SOURCE_ID)
layer.iconImage = .constant(.name(Constants.RED_ICON_ID))
layer.iconAnchor = .constant(.bottom)
layer.iconOffset = .constant([0, 12])
try? mapView.mapboxMap.addLayer(layer)
}
}

extension ViewController {
private enum Constants {
static let RED_ICON_ID = "red"
static let SOURCE_ID = "source_id"
static let LAYER_ID = "layer_id"
static let coordinate = CLLocationCoordinate2D(latitude: 55.665957, longitude: 12.550343)
}
}
このexampleは役に立ちましたか?