Show Line Data from GeoJSON File on the Map
This example demonstrates how to use annotations to display marker on the map.
You will learn the following:
- What are annotations
- How to display marker on the map using annotations.
View complete source code on GitHub
Annotations
Annotations provide an interface that will look familiar if you’ve used annotations in MapKit. It has built-in dragging and selection support. But using annotations is not recommended if you need to add a large number of markers to a map, or if you also need to style annotations differently based on a specific data property. If your project includes those requirements, consider using our more performant MGLStyleLayer
classes.
Any MGLPointAnnotation
, MGLLine
, or MGLPolygon
that conforms to the MGLAnnotation
protocol can be used to annotate the map to mark a place with a specific shape.
By implementing optional MGLMapViewDelegate
, you can customize the basic styling of annotations. Commonly implemented delegate methods include:
-mapView:viewForAnnotation
: returns anMGLAnnotationView
that can associate aUIView
with a specificMGLPointAnnotation
.-mapView:imageForAnnotation
: returns anMGLAnnotationImage
that can associate aUIImage
with a specificMGLPointAnnotation
.-mapView:didSelectAnnotation
: is called when an annotation is tapped on.-mapView:annotationCanShowCallout
: returns a boolean value indicating whether the annotation can display additional information inside a callout.
Add annotation on the map
After the style has been loaded
- We create
MGLPointAnnotation
and set its coordinate to the center of the screen. - Then we create the
MGLShapeSource
with shape being the annotation created in previous step andMGLSymbolStyleLayer
to show the shape from the source on the map. - Next we load the image and register it a style sprite.
- Finally we add source and layer created in previous steps to the style.
func createMarkerSymbol(_ mapView: MGLMapView, _ style: MGLStyle) {
// Create point to represent where the symbol should be placed
let point = MGLPointAnnotation()
point.coordinate = mapView.centerCoordinate
// Create a data source to hold the point data
let shapeSource = MGLShapeSource(identifier: "marker-source", shape: point, options: nil)
// Create a style layer for the symbol
let shapeLayer = MGLSymbolStyleLayer(identifier: "marker-style", source: shapeSource)
// Add the image to the style's sprite
if let image = UIImage(named: "house-icon") {
style.setImage(image, forName: "home-symbol")
}
// Tell the layer to use the image in the sprite
shapeLayer.iconImageName = NSExpression(forConstantValue: "home-symbol")
// Add the source and style layer to the map
style.addSource(shapeSource)
style.addLayer(shapeLayer)
}