]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/diary_entry.js
Fix map controls in user diary form
[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     const geolocateControl = new OSM.MapLibre.GeolocateControl();
41     map.addControl(new OSM.MapLibre.CombinedControlGroup([navigationControl, geolocateControl]), position);
42
43     // Create marker if coordinates exist when map is shown
44     if ($("#latitude").val() && $("#longitude").val()) {
45       const lngLat = new maplibregl.LngLat($("#longitude").val(), $("#latitude").val());
46       setLocation({ lngLat });
47       map.setCenter(lngLat);
48     }
49
50     map.on("click", setLocation);
51   });
52 });