Custom Annotations

This example shows how to add custom annotations in MapView.

  • Add Annotations from GeoJson

  • Animate Annotations

  • Query Visible Annotations in Rect

  • Center Selected Annotation

docs-image

For all code examples, refer to Maps Code Examples

AnnotationsViewController view source

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
//
//  StyleMapLayerViewController.swift
//  maps-ios-demo
//

import Foundation
import UIKit
import Nbmap

enum AnnotationActionType{
    case AddAnnotations
    case AddNumberAnnotations
    case AnimateAnnotations
    case QueryVisibleAnnotations
    case CenterSelectedAnnotations
    case AddVisibleAreaPolyline

}

class AnnotationsViewController: UIViewController {
    
    var nbMapView: NGLMapView! {
        didSet {
            oldValue?.removeFromSuperview()
            if let mapView = nbMapView {
                view.insertSubview(mapView, at: 0)
                mapView.delegate = self
            }
        }
    }
    var button: UIButton!
    
    let typeList = [
        AnnotationActionType.AddAnnotations,
        AnnotationActionType.AddNumberAnnotations,
        AnnotationActionType.AnimateAnnotations,
        AnnotationActionType.QueryVisibleAnnotations,
        AnnotationActionType.CenterSelectedAnnotations,
        AnnotationActionType.AddVisibleAreaPolyline,
    ]
    
    
    var points : Array = [CLLocationCoordinate2D]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        nbMapView = NGLMapView(frame:self.view.bounds)
        button = UIButton(type: .system)
        button.setTitle("Settings", for: .normal)
        button.addTarget(self, action: #selector(showSetings), for: .touchUpInside)
        button.frame = CGRect(x: 0, y: 0, width: 100, height: 40)
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button)
    }
    
    @objc func showSetings() {
        let tableViewController = UITableViewController(style: .plain)
        tableViewController.tableView.delegate = self
        tableViewController.tableView.dataSource = self
        tableViewController.title = "Camera Settings"
        self.present(tableViewController, animated: true)
    }
    
    func performeSettings(type: AnnotationActionType) {
        switch type {
        case AnnotationActionType.AddAnnotations :
            addAnnotations(count: 100)
            break
        case AnnotationActionType.AddNumberAnnotations :
            addAnnotations(count: 1000)
            break
        case .AnimateAnnotations:
            animateAnnotations()
            break
        case .QueryVisibleAnnotations:
            queryVisibleAnnotations()
            break
        case .CenterSelectedAnnotations:
            centerSelectedAnnotation()
            break
        case .AddVisibleAreaPolyline:
            addVisibleAreaPolyline()
            break
        }
        
    }
    
    func addAnnotations(count: Int32) {
        
        if let annotations = self.nbMapView.annotations {
            self.nbMapView.removeAnnotations(annotations)
        }

        DispatchQueue.global(qos: .default).async {
            if let featuresData = try? Data(contentsOf: Bundle.main.url(forResource: "points", withExtension: "geojson")!),
                let features = try? JSONSerialization.jsonObject(with: featuresData, options: []) as? [String: Any] {
                
                var annotations = [NGLPointAnnotation]()
                
                if let featureList = features["features"] as? [[String: Any]] {
                    for feature in featureList {
                        if let coordinates = feature["geometry"] as? [String: Any],
                           let coordinateList = coordinates["coordinates"] as? [Double],
                           let title = feature["properties"] as? [String: Any] {
                            
                            let coordinate = CLLocationCoordinate2D(latitude: coordinateList[1], longitude: coordinateList[0])
                            let annotation = NGLPointAnnotation()
                            annotation.coordinate = coordinate
                            annotation.title = title["NAME"] as? String
                            
                            annotations.append(annotation)
                            
                            if annotations.count == count {
                                break
                            }
                        }
                    }
                    
                    DispatchQueue.main.async {
                        self.nbMapView.addAnnotations(annotations)
                        self.nbMapView.showAnnotations(annotations, animated: true)
                    }
                }
            }
        }

    }
    
    func animateAnnotations () {
        let annot = NGLPointAnnotation()
        annot.coordinate = self.nbMapView.centerCoordinate
        self.nbMapView.addAnnotation(annot)

        let point = CGPoint(x: self.view.frame.origin.x + 200, y: self.view.frame.midY)
        let coord = self.nbMapView.convert(point, toCoordinateFrom: self.view)

        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
            UIView.animate(withDuration: 1) {
                annot.coordinate = coord
            }
        }

    }
    
    func queryVisibleAnnotations() {
        let visibleAnnotationCount = NSNumber(value: self.nbMapView.visibleAnnotations?.count ?? 0)
        var message: String

        if visibleAnnotationCount.intValue == 1 {
            message = "There is \(visibleAnnotationCount) visible annotation."
        } else {
            message = "There are \(visibleAnnotationCount) visible annotations."
        }

        let alertController = UIAlertController(title: "Visible Annotations", message: message, preferredStyle: .alert)
        alertController.addAction(UIAlertAction(title: "Ok", style: .cancel, handler: nil))
        self.present(alertController, animated: true, completion: nil)

    }
    
    func centerSelectedAnnotation() {
        
        if let annotation = self.nbMapView.selectedAnnotations.first {
            let point = self.nbMapView.convert(annotation.coordinate, toPointTo: self.nbMapView)
            let center = self.nbMapView.convert(point, toCoordinateFrom: self.nbMapView)
            self.nbMapView.setCenter(center, animated: true)
        }
    }

    func addVisibleAreaPolyline() {
        let constrainedRect = self.nbMapView.bounds.inset(by: self.nbMapView.contentInset)

        var lineCoords = [CLLocationCoordinate2D]()

        lineCoords.append(self.nbMapView.convert(CGPoint(x: constrainedRect.minX, y: constrainedRect.minY), toCoordinateFrom: self.nbMapView))
        lineCoords.append(self.nbMapView.convert(CGPoint(x: constrainedRect.maxX, y: constrainedRect.minY), toCoordinateFrom: self.nbMapView))
        lineCoords.append(self.nbMapView.convert(CGPoint(x: constrainedRect.maxX, y: constrainedRect.maxY), toCoordinateFrom: self.nbMapView))
        lineCoords.append(self.nbMapView.convert(CGPoint(x: constrainedRect.minX, y: constrainedRect.maxY), toCoordinateFrom: self.nbMapView))
        lineCoords.append(lineCoords[0])

        let line = NGLPolyline(coordinates: &lineCoords, count: UInt(lineCoords.count))
        self.nbMapView.addAnnotation(line)

    }
    
  
}


extension AnnotationsViewController: NGLMapViewDelegate {
    func mapView(_ mapView: NGLMapView, didFinishLoading style: NGLStyle){
        nbMapView.setCenter(CLLocationCoordinate2DMake(38.87031006108791, -77.00896639534831), zoomLevel: 10, animated: true)
        
    }
    
    func mapView(_ mapView: NGLMapView, didSelect annotation: NGLAnnotation) {
        let point = self.nbMapView.convert(annotation.coordinate, toPointTo: self.nbMapView)
        let center = self.nbMapView.convert(point, toCoordinateFrom: self.nbMapView)
        self.nbMapView.setCenter(center, zoomLevel: 14, animated: true)
    }
    
    func mapView(_ mapView: NGLMapView, annotationCanShowCallout annotation: NGLAnnotation) -> Bool {
        return true
    }
}

extension AnnotationsViewController: UITableViewDelegate, UITableViewDataSource {
    
    func settingsTitlesForRaw(index: Int) -> String {
        let type = typeList[index]
        switch type {
        case AnnotationActionType.AddAnnotations :
            return "Add 100 Annotations"
        case AnnotationActionType.AddNumberAnnotations :
            return "Add 1000 Annotations"
        case AnnotationActionType.AnimateAnnotations :
            return "Animate Annotations"
        case AnnotationActionType.QueryVisibleAnnotations :
            return "Query Visible Annotations"
        case AnnotationActionType.CenterSelectedAnnotations :
            return "Center Selected Annotations"
        case AnnotationActionType.AddVisibleAreaPolyline :
            return "Add Visible Area Polyline"
        }
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return typeList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .default, reuseIdentifier: nil)
        cell.textLabel?.text = settingsTitlesForRaw(index: indexPath.row)
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.isHidden = true
        let type = typeList[indexPath.row]
        dismissSettings(type: type)
    }
    
    func dismissSettings(type: AnnotationActionType) {
        dismiss(animated: true)
        performeSettings(type: type)
    }
}
  1. Initializing nbMapView:

    • The nbMapView is initialized with a frame that matches the bounds of the view controller's view.

    • The mapView is added as a subview of the view controller's view and set as the delegate of the map view.

  2. addAnnotations:

    • Removes any existing annotations from the map view.

    • Asynchronously loads a GeoJSON file named "points.geojson" from the main bundle.

    • Parses the GeoJSON data and extracts the coordinates and title for each feature.

    • Creates NGLPointAnnotation objects for each feature and adds them to an array.

    • Adds the annotations to the map view and shows them with an animated effect.

3 queryVisibleAnnotations:

  • Retrieves the count of visible annotations on the map view using nbMapView.visibleAnnotations.

  • Displays an alert controller with a message indicating the number of visible annotations.

  1. centerSelectedAnnotation:

    • Checks if there is a selected annotation on the map view using nbMapView.selectedAnnotations.

    • Converts the coordinate of the selected annotation to a point on the map view.

    • Converts the point to a coordinate on the map view.

    • Sets the map view's center coordinate to the new coordinate with an animated effect using nbMapView.setCenter(center, animated: true).

4 addVisibleAreaPolyline:

  • Creates a rectangle (constrainedRect) that represents the visible area of the map view.

  • Converts the four corners of the rectangle to coordinates on the map view.

  • Creates an NGLPolyline with the converted coordinates and adds it as an annotation to the map view.

Have Questions ?