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