]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/index/layers/notes.js
Abort loading when note layer is removed
[rails.git] / app / assets / javascripts / index / layers / notes.js
1 OSM.initializeNotesLayer = function (map) {
2   let noteLoader;
3   const noteLayer = map.noteLayer;
4   let notes = {};
5
6   var noteIcons = {
7     "new": L.icon({
8       iconUrl: OSM.NEW_NOTE_MARKER,
9       iconSize: [25, 40],
10       iconAnchor: [12, 40]
11     }),
12     "open": L.icon({
13       iconUrl: OSM.OPEN_NOTE_MARKER,
14       iconSize: [25, 40],
15       iconAnchor: [12, 40]
16     }),
17     "closed": L.icon({
18       iconUrl: OSM.CLOSED_NOTE_MARKER,
19       iconSize: [25, 40],
20       iconAnchor: [12, 40]
21     })
22   };
23
24   noteLayer.on("add", () => {
25     loadNotes();
26     map.on("moveend", loadNotes);
27     map.fire("overlayadd", { layer: noteLayer });
28   }).on("remove", () => {
29     if (noteLoader) noteLoader.abort();
30     noteLoader = null;
31     map.off("moveend", loadNotes);
32     noteLayer.clearLayers();
33     notes = {};
34     map.fire("overlayremove", { layer: noteLayer });
35   }).on("click", function (e) {
36     if (e.layer.id) {
37       OSM.router.route("/note/" + e.layer.id);
38     }
39   });
40
41   function updateMarker(old_marker, feature) {
42     var marker = old_marker;
43     if (marker) {
44       marker.setIcon(noteIcons[feature.properties.status]);
45     } else {
46       marker = L.marker(feature.geometry.coordinates.reverse(), {
47         icon: noteIcons[feature.properties.status],
48         title: feature.properties.comments[0].text,
49         opacity: 0.8,
50         interactive: true
51       });
52       marker.id = feature.properties.id;
53       marker.addTo(noteLayer);
54     }
55     return marker;
56   }
57
58   noteLayer.getLayerId = function (marker) {
59     return marker.id;
60   };
61
62   function loadNotes() {
63     var bounds = map.getBounds();
64     var size = bounds.getSize();
65
66     if (size <= OSM.MAX_NOTE_REQUEST_AREA) {
67       var url = "/api/" + OSM.API_VERSION + "/notes.json?bbox=" + bounds.toBBoxString();
68
69       if (noteLoader) noteLoader.abort();
70
71       noteLoader = $.ajax({
72         url: url,
73         success: success
74       });
75     }
76
77     function success(json) {
78       var oldNotes = notes;
79       notes = {};
80       json.features.forEach(updateMarkers);
81
82       function updateMarkers(feature) {
83         var marker = oldNotes[feature.properties.id];
84         delete oldNotes[feature.properties.id];
85         notes[feature.properties.id] = updateMarker(marker, feature);
86       }
87
88       for (var id in oldNotes) {
89         noteLayer.removeLayer(oldNotes[id]);
90       }
91
92       noteLoader = null;
93     }
94   }
95 };