QGIS-Leaflet (Настройка события OnClick) - PullRequest
2 голосов
/ 16 октября 2019

У меня возникают трудности при добавлении кода для настройки действий / событий при нажатии на многоугольник с помощью веб-карты Leaflet.

Конечная цель - не только показать это маленькое всплывающее окно, но и HTML-код информационного слайдера, который нужнодобавил сам. В настоящее время я подозреваю, что это может быть место для добавления или изменения чего-либо, но не совсем уверен:

function pop_LotDrawing_2(feature, layer) {
        layer.on({
            mouseout: function(e) {
                for (i in e.target._eventParents) {
                    e.target._eventParents[i].resetStyle(e.target);
                }
            },
            mouseover: highlightFeature,
        });
        var popupContent = '<table>\
                <tr>\
                    <td colspan="2"><strong>Lot</strong><br />' + (feature.properties['Lot'] !== null ? Autolinker.link(String(feature.properties['Lot'])) : '') + '</td>\
                </tr>\
                <tr>\
                    <th scope="row">Design</th>\
                    <td>' + (feature.properties['Design'] !== null ? Autolinker.link(String(feature.properties['Design'])) : '') + '</td>\
                </tr>\
                <tr>\
                    <th scope="row">Area (sqm)</th>\
                    <td>' + (feature.properties['Area (sqm)'] !== null ? Autolinker.link(String(feature.properties['Area (sqm)'])) : '') + '</td>\
                </tr>\
            </table>';
        layer.bindPopup(popupContent, {maxHeight: 400});

В конце концов, я хочу реализовать что-то вроде этого сайта: http://novieveshki.ru/map/

введите описание изображения здесь

1 Ответ

1 голос
/ 16 октября 2019

Один из способов сделать это может состоять в создании массива, который будет содержать все ваши функции многоугольника. Вы можете добавить все свои полигоны в этот массив, а затем перебрать элементы в массиве, чтобы прикрепить обработчик событий и добавить его на карту. Вы можете прикрепить обработчик событий, используя polygon.on().

Вот пример, где я добавляю круг и треугольник на карту. Я даю описание обеих этих форм. Затем я добавляю их в массив polygons и, как только они инициализируются, я зацикливаюсь на массиве, чтобы прикрепить обработчик событий и добавить их на карту. Нажмите «Run Snippet», чтобы попробовать (вероятно, будет легче увидеть его в полноэкранном режиме).

Вы можете оформить боковую панель так, как вам нравится, и изменить обработчик событий и / илиCSS, чтобы создать эффект анимации, если это необходимо.

Надеюсь, что вы получите правильный путь.

let map = new L.Map('map');
// polygons array to hold all polygons
let polygons = [];

L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  attribution: '&copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors',
  maxZoom: 18
}).addTo(map);

// Location to center the map
let london = new L.LatLng(51.505, -0.09);
map.setView(london, 13);

// Create a circle around a point
let circleLocation = new L.LatLng(51.508, -0.11),
  circleOptions = {
    color: 'red',
    fillColor: '#f03',
    fillOpacity: 0.5
  };

let circle = new L.Circle(circleLocation, 500, circleOptions);
// This is what will be displayed in the sidebar on click
circle.desc = "You clicked a circle!";
// Add the circle to the polygons array
polygons.push(circle);

// Create a triangle with vertices below
let p1 = new L.LatLng(51.509, -0.08),
  p2 = new L.LatLng(51.503, -0.06),
  p3 = new L.LatLng(51.51, -0.047),
  polygonPoints = [p1, p2, p3];

let polygon = new L.Polygon(polygonPoints);
// This is what will be displayed in the sidebar on click
polygon.desc = "You clicked a triangle!";
// Add the triangle to the polygons array
polygons.push(polygon);

// Loop over all elements in the polygons array and attach the event handler and add the element to the map
polygons.forEach(function (i) {
	i.on("click", changeSidebar);
  map.addLayer(i);
});

// Basic event handler that just changes the sidebar innerHTML to the element's `desc` property defined above.
function changeSidebar (event) {
	sidebar.innerHTML = event.target.desc;
}
#sidebar {
  width: 30%;
  height: 500px;
  position: absolute;
  right: 0;
  background-color: #c3c3c3;
}

#map {
  width: 70%;
  height: 500px;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.5.1/leaflet.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.5.1/leaflet.js"></script>
<div id="sidebar"></div>
<div id="map"></div>
...