]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/index/layers/notes.js
Merge remote-tracking branch 'upstream/pull/5925'
[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   noteLayer.on("add", () => {
7     loadNotes();
8     map.on("moveend", loadNotes);
9     map.fire("overlayadd", { layer: noteLayer });
10   }).on("remove", () => {
11     if (noteLoader) noteLoader.abort();
12     noteLoader = null;
13     map.off("moveend", loadNotes);
14     noteLayer.clearLayers();
15     notes = {};
16     map.fire("overlayremove", { layer: noteLayer });
17   }).on("click", function (e) {
18     if (e.layer.id) {
19       OSM.router.route("/note/" + e.layer.id);
20     }
21   });
22
23   function updateMarker(old_marker, feature) {
24     let marker = old_marker;
25     if (marker) {
26       marker.setIcon(OSM.getMarker({ icon: `${feature.properties.status}_NOTE_MARKER`, shadow: false, height: 40 }));
27     } else {
28       let title;
29       const description = feature.properties.comments[0];
30
31       if (description?.action === "opened") {
32         title = description.text;
33       }
34
35       marker = L.marker(feature.geometry.coordinates.reverse(), {
36         icon: OSM.getMarker({ icon: `${feature.properties.status}_NOTE_MARKER`, shadow: false, height: 40 }),
37         title,
38         opacity: 0.8,
39         interactive: true
40       });
41       marker.id = feature.properties.id;
42       marker.addTo(noteLayer);
43     }
44     return marker;
45   }
46
47   noteLayer.getLayerId = function (marker) {
48     return marker.id;
49   };
50
51   function loadNotes() {
52     const bounds = map.getBounds();
53     const size = bounds.getSize();
54
55     if (size <= OSM.MAX_NOTE_REQUEST_AREA) {
56       const url = "/api/" + OSM.API_VERSION + "/notes.json?bbox=" + bounds.toBBoxString();
57
58       if (noteLoader) noteLoader.abort();
59
60       noteLoader = new AbortController();
61       fetch(url, { signal: noteLoader.signal })
62         .then(response => response.json())
63         .then(success)
64         .catch(() => {})
65         .finally(() => noteLoader = null);
66     }
67
68     function success(json) {
69       const oldNotes = notes;
70       notes = {};
71       for (const feature of json.features) {
72         const marker = oldNotes[feature.properties.id];
73         delete oldNotes[feature.properties.id];
74         notes[feature.properties.id] = updateMarker(marker, feature);
75       }
76
77       for (const id in oldNotes) {
78         noteLayer.removeLayer(oldNotes[id]);
79       }
80     }
81   }
82 };