demarches-normaliennes/app/javascript/old_design/carto.js

82 lines
1.8 KiB
JavaScript
Raw Normal View History

2018-10-03 10:39:35 +02:00
import L from 'leaflet';
import FreeDraw, { NONE, CREATE } from 'leaflet-freedraw';
import { fire, on, getJSON } from '@utils';
import { getData } from '../shared/data';
import { initMap } from '../shared/carto';
import polygonArea from './carto/polygon_area';
import drawFactory from './carto/draw';
function initialize() {
if (document.getElementById('map')) {
const data = getData('carto');
const position = data.position;
const map = initMap(position);
const freeDraw = new FreeDraw({
mode: NONE,
smoothFactor: 4,
mergePolygons: false
});
map.addLayer(freeDraw);
addEventFreeDraw(freeDraw);
addEventSearchAddress(map);
const cartoDrawZones = drawFactory(map, freeDraw);
window.DS = { cartoDrawZones };
2018-10-03 10:39:35 +02:00
cartoDrawZones(data);
if (freeDraw.polygons[0]) {
map.setZoom(18);
map.fitBounds(freeDraw.polygons[0].getBounds());
2018-10-03 10:39:35 +02:00
}
}
}
addEventListener('turbolinks:load', initialize);
function addEventFreeDraw(freeDraw) {
freeDraw.on('markers', ({ latLngs }) => {
const input = document.querySelector('input[name=selection]');
if (polygonArea(latLngs) < 300000) {
input.value = JSON.stringify(latLngs);
2018-10-03 10:39:35 +02:00
} else {
input.value = '{ "error": "TooManyPolygons" }';
2018-10-03 10:39:35 +02:00
}
fire(input, 'change');
2017-04-04 16:15:33 +02:00
});
on('#map', 'click', () => {
2018-10-03 10:39:35 +02:00
freeDraw.mode(NONE);
2017-04-04 16:15:33 +02:00
});
on('#new', 'click', () => {
2018-10-03 10:39:35 +02:00
freeDraw.mode(CREATE);
2017-04-04 16:15:33 +02:00
});
}
2018-10-03 10:39:35 +02:00
function getAddressPoint(map, request) {
getJSON('/address/geocode', { request }).then(data => {
2018-10-03 10:39:35 +02:00
if (data.lat !== null) {
map.setView(new L.LatLng(data.lat, data.lon), data.zoom);
}
2017-04-04 16:15:33 +02:00
});
2015-11-25 10:26:55 +01:00
}
2018-10-03 10:39:35 +02:00
function addEventSearchAddress(map) {
on(
'#search-by-address input[type=address]',
2018-10-03 10:39:35 +02:00
'autocomplete:select',
(_, seggestion) => {
getAddressPoint(map, seggestion['label']);
}
);
2016-06-09 16:28:44 +02:00
}