]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/diary_entry.js
Extend MapLibre GeolocateControl class
[rails.git] / app / assets / javascripts / diary_entry.js
1 //= require maplibre.map
2 //= require maplibre/controls
3 //= require maplibre/dom_util
4
5 $(function () {
6   let marker, map;
7
8   function updateFormFieldsFromMarkerPosition() {
9     const lngLat = marker.getLngLat();
10     $("#latitude").val(lngLat.lat);
11     $("#longitude").val(lngLat.lng);
12   }
13
14   function setLocation(e) {
15     const coords = e.lngLat.wrap();
16     if (marker) {
17       marker.setLngLat(coords);
18     } else {
19       marker = new OSM.MapLibre.Marker({ draggable: true })
20         .setLngLat(coords)
21         .setPopup(new OSM.MapLibre.Popup().setHTML(OSM.i18n.t("diary_entries.edit.marker_text")))
22         .addTo(map);
23       marker.on("dragend", updateFormFieldsFromMarkerPosition);
24     }
25     updateFormFieldsFromMarkerPosition();
26   }
27
28   $("#usemap").click(function (e) {
29     e.preventDefault();
30
31     $("#map").show();
32     $("#usemap").hide();
33
34     const params = $("#map").data();
35     map = new maplibregl.Map({
36       ...OSM.MapLibre.defaultSecondaryMapOptions,
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     map.touchZoomRotate.disableRotation();
45     map.keyboard.disableRotation();
46
47     // Create marker if coordinates exist when map is shown
48     if ($("#latitude").val() && $("#longitude").val()) {
49       const lngLat = new maplibregl.LngLat($("#longitude").val(), $("#latitude").val());
50       setLocation({ lngLat });
51       map.setCenter(lngLat);
52     }
53
54     map.on("click", setLocation);
55   });
56 });