]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/diary_entry.js
Extend MapLibre Map class
[rails.git] / app / assets / javascripts / diary_entry.js
1 //= require maplibre.map
2 //= require maplibre/map
3 //= require maplibre/controls
4 //= require maplibre/dom_util
5
6 $(function () {
7   let marker, map;
8
9   function updateFormFieldsFromMarkerPosition() {
10     const lngLat = marker.getLngLat();
11     $("#latitude").val(lngLat.lat);
12     $("#longitude").val(lngLat.lng);
13   }
14
15   function setLocation(e) {
16     const coords = e.lngLat.wrap();
17     if (marker) {
18       marker.setLngLat(coords);
19     } else {
20       marker = new OSM.MapLibre.Marker({ draggable: true })
21         .setLngLat(coords)
22         .setPopup(new OSM.MapLibre.Popup().setHTML(OSM.i18n.t("diary_entries.edit.marker_text")))
23         .addTo(map);
24       marker.on("dragend", updateFormFieldsFromMarkerPosition);
25     }
26     updateFormFieldsFromMarkerPosition();
27   }
28
29   $("#usemap").click(function (e) {
30     e.preventDefault();
31
32     $("#map").show();
33     $("#usemap").hide();
34
35     const params = $("#map").data();
36     map = new OSM.MapLibre.SecondaryMap({
37       center: [params.lon, params.lat],
38       zoom: params.zoom - 1
39     });
40
41     const position = $("html").attr("dir") === "rtl" ? "top-left" : "top-right";
42     const navigationControl = new OSM.MapLibre.NavigationControl();
43     map.addControl(navigationControl, position);
44
45     // Create marker if coordinates exist when map is shown
46     if ($("#latitude").val() && $("#longitude").val()) {
47       const lngLat = new maplibregl.LngLat($("#longitude").val(), $("#latitude").val());
48       setLocation({ lngLat });
49       map.setCenter(lngLat);
50     }
51
52     map.on("click", setLocation);
53   });
54 });