Refactor carto code

This commit is contained in:
Paul Chavard 2018-10-03 10:39:35 +02:00
parent 51127c324d
commit 37d424d671
9 changed files with 211 additions and 214 deletions

View file

@ -5,8 +5,6 @@
#carte-page {
#map {
margin-left: 15px;
width: 90%;
height: 600px;
}
@ -39,22 +37,11 @@
}
}
#map section.overlay {
position: absolute;
top: 0;
left: 0;
pointer-events: none;
box-shadow: inset -100px 0 100px -100px rgba(0, 0, 0, 0.25);
width: 100%;
height: 100%;
z-index: 2001;
}
#map.mode-create {
cursor: url("/assets/pencil.png"), crosshair !important;
}
#map g path.tracer {
#map g path.leaflet-polygon {
transition: all 0.25s;
stroke-width: 4px;
stroke-opacity: 1;
@ -73,7 +60,7 @@
fill: #4D4D4D !important;
}
#map div.polygon-elbow {
#map div.leaflet-edge {
box-shadow: 0 0 0 2px #FFFFFF, 0 0 10px rgba(0, 0, 0, 0.35);
border: 5px solid #D7217E;
border-radius: 10px;
@ -86,27 +73,11 @@
height: 0 !important;
}
#map div.polygon-elbow.non-polygon {
opacity: 0 !important;
pointer-events: none !important;
border: 5px solid #A9A9A9;
}
#map.mode-edit div.polygon-elbow {
#map.mode-edit div.leaflet-edge {
opacity: 1;
pointer-events: all;
}
#map svg.tracer {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 2001;
pointer-events: none;
}
.info {
padding: 6px 8px;
font: 14px/16px Arial, Helvetica, sans-serif;

View file

@ -2,6 +2,7 @@ import $ from 'jquery';
import L from 'leaflet';
import { getData } from '../shared/data';
import { DEFAULT_POSITION } from '../shared/carto';
import {
drawCadastre,
@ -9,10 +10,6 @@ import {
drawUserSelection
} from './carto/draw';
const LON = '2.428462';
const LAT = '46.538192';
const DEFAULT_POSITION = { lon: LON, lat: LAT, zoom: 5 };
function initialize() {
if ($('#map').length > 0) {
$.getJSON(getData('carto').getPositionUrl).then(

View file

@ -1,159 +1,177 @@
var LON = '2.428462';
var LAT = '46.538192';
import L from 'leaflet';
import area from '@turf/area';
import FreeDraw, { NONE, EDIT, CREATE, DELETE } from 'leaflet-freedraw';
import $ from 'jquery';
function initCarto() {
OSM = L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
});
import { getData } from '../shared/data';
import { DEFAULT_POSITION, LAT, LON } from '../shared/carto';
import { qpActive, displayQP, getQP } from './carto/qp';
import { cadastreActive, displayCadastre, getCadastre } from './carto/cadastre';
position = get_position() || default_gestionnaire_position();
function initialize() {
if ($('#map').length > 0) {
getPosition(getData('carto').dossierId).then(
position => initializeWithPosition(position),
() => initializeWithPosition(DEFAULT_POSITION)
);
}
}
map = L.map("map", {
addEventListener('turbolinks:load', initialize);
function initializeWithPosition(position) {
const OSM = L.tileLayer(
'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
{
attribution:
'&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
}
);
const map = L.map('map', {
center: new L.LatLng(position.lat, position.lon),
zoom: position.zoom,
layers: [OSM],
scrollWheelZoom: false
});
icon = L.icon({
iconUrl: '/assets/marker-icon.png',
//shadowUrl: 'leaf-shadow.png',
if (qpActive()) {
displayQP(map, getJsonValue('#quartier_prioritaires'));
}
iconSize: [34.48, 40], // size of the icon
//shadowSize: [50, 64], // size of the shadow
iconAnchor: [20, 20] // point of the icon which will correspond to marker's location
//shadowAnchor: [4, 62], // the same for the shadow
//popupAnchor: [-3, -76] // point from which the popup should open relative to the iconAnchor
if (cadastreActive()) {
displayCadastre(map, getJsonValue('#cadastres'));
}
const freeDraw = new FreeDraw({
mode: NONE,
smoothFactor: 4,
mergePolygons: false
});
if (qp_active())
display_qp(JSON.parse($("#quartier_prioritaires").val()));
if (cadastre_active())
display_cadastre(JSON.parse($("#cadastres").val()));
freeDraw = new L.FreeDraw();
freeDraw.options.setSmoothFactor(4);
freeDraw.options.simplifyPolygon = false;
map.addLayer(freeDraw);
if ($("#json_latlngs").val() != '' && $("#json_latlngs").val() != '[]') {
const latLngs = getJsonValue('#json_latlngs');
if (latLngs.length) {
map.setZoom(18);
$.each($.parseJSON($("#json_latlngs").val()), function (i, val) {
freeDraw.createPolygon(val);
});
for (let polygon of latLngs) {
freeDraw.createPolygon(polygon);
}
map.fitBounds(freeDraw.polygons[0].getBounds());
}
else if (position.lat == LAT && position.lon == LON)
} else if (position.lat == LAT && position.lon == LON) {
map.setView(new L.LatLng(position.lat, position.lon), position.zoom);
}
add_event_freeDraw();
add_event_search_address();
addEventFreeDraw(map, freeDraw);
addEventSearchAddress(map);
}
function default_gestionnaire_position() {
return {lon: LON, lat: LAT, zoom: 5}
}
function getExternalData(map, latLngs) {
const { dossierId } = getData('carto');
function get_external_data(latLngs) {
if (qp_active())
display_qp(get_qp(latLngs));
if (qpActive()) {
getQP(dossierId, latLngs).then(qps => displayQP(map, qps));
}
if (cadastre_active()) {
polygons = {"type": "FeatureCollection", "features": []};
if (cadastreActive()) {
const polygons = { type: 'FeatureCollection', features: [] };
for (i = 0; i < latLngs.length; i++)
polygons.features.push(feature_polygon_latLngs(latLngs[i]))
for (let i = 0; i < latLngs.length; i++) {
polygons.features.push(featurePolygonLatLngs(latLngs[i]));
}
cadastre_list = [{zoom_error: true}];
if (turf_area(polygons) < 300000)
cadastre_list = get_cadastre(latLngs);
display_cadastre(cadastre_list);
if (area(polygons) < 300000) {
getCadastre(dossierId, latLngs).then(cadastres =>
displayCadastre(map, cadastres)
);
} else {
displayCadastre(map, [{ zoom_error: true }]);
}
}
}
function feature_polygon_latLngs(coordinates) {
return ({
"type": "Feature",
"properties": {},
"geometry": {
"type": "Polygon",
"coordinates": [
JSON.parse(L.FreeDraw.Utilities.getJsonPolygons([coordinates]))['latLngs']
]
function featurePolygonLatLngs(coordinates) {
return {
type: 'Feature',
properties: {},
geometry: {
type: 'Polygon',
coordinates: [JSON.parse(getJsonPolygons([coordinates]))['latLngs']]
}
})
};
}
function add_event_freeDraw() {
freeDraw.on('markers', function (e) {
$("#json_latlngs").val(JSON.stringify(e.latLngs));
function addEventFreeDraw(map, freeDraw) {
freeDraw.on('markers', ({ latLngs }) => {
$('#json_latlngs').val(JSON.stringify(latLngs));
add_event_edit();
addEventEdit(freeDraw);
get_external_data(e.latLngs);
getExternalData(map, latLngs);
});
$("#map").on('click', function(){
freeDraw.setMode(L.FreeDraw.MODES.VIEW);
$('#map').on('click', () => {
freeDraw.mode(NONE);
});
$("#new").on('click', function (e) {
freeDraw.setMode(L.FreeDraw.MODES.CREATE);
});
$("#delete").on('click', function (e) {
freeDraw.setMode(L.FreeDraw.MODES.DELETE);
$('#new').on('click', () => {
freeDraw.mode(CREATE);
});
}
function add_event_edit (){
$(".leaflet-container g path").on('click', function (e) {
setTimeout(function(){freeDraw.setMode(L.FreeDraw.MODES.EDIT | L.FreeDraw.MODES.DELETE)}, 50);
function addEventEdit(freeDraw) {
$('.leaflet-container svg').removeAttr('pointer-events');
$('.leaflet-container g path').on('click', () => {
setTimeout(function() {
freeDraw.mode(EDIT | DELETE);
}, 50);
});
}
function get_position() {
var position;
$.ajax({
url: '/users/dossiers/' + dossier_id + '/carte/position',
dataType: 'json',
async: false
}).done(function (data) {
position = data
});
return position;
function getPosition(dossierId) {
return $.getJSON(`/users/dossiers/${dossierId}/carte/position`);
}
function get_address_point(request) {
$.get('/ban/address_point', { request: request })
.done(function (data) {
if (data.lat !== null) {
map.setView(new L.LatLng(data.lat, data.lon), data.zoom);
}
function getAddressPoint(map, request) {
$.get('/ban/address_point', { request }).then(data => {
if (data.lat !== null) {
map.setView(new L.LatLng(data.lat, data.lon), data.zoom);
}
});
}
function addEventSearchAddress(map) {
$("#search-by-address input[type='address']").on(
'autocomplete:select',
(_, seggestion) => {
getAddressPoint(map, seggestion['label']);
}
);
}
function getJsonValue(selector) {
let data = document.querySelector(selector).value;
if (data && data !== '[]') {
return JSON.parse(data);
}
return [];
}
function getJsonPolygons(latLngGroups) {
var groups = [];
latLngGroups.forEach(function forEach(latLngs) {
var group = [];
latLngs.forEach(function forEach(latLng) {
group.push('[' + latLng.lng + ', ' + latLng.lat + ']');
});
}
function jsObject_to_array(qp_list) {
return Object.keys(qp_list).map(function (v) {
return qp_list[v];
});
}
function add_event_search_address() {
$("#search-by-address input[type='address']").bind('autocomplete:select', function (ev, suggestion) {
get_address_point(suggestion['label']);
groups.push('{ "latLngs": [' + group.join(', ') + '] }');
});
$("#search-by-address input[type='address']").keypress(function (e) {
if (e.keyCode == 13)
get_address_point($(this).val());
});
return groups;
}

View file

@ -1,39 +1,44 @@
function cadastre_active() {
return $("#map.cadastre").length > 0
import L from 'leaflet';
import $ from 'jquery';
export function cadastreActive() {
return $('#map.cadastre').length > 0;
}
function get_cadastre(coordinates) {
if (!cadastre_active())
return;
var cadastre;
$.ajax({
export function getCadastre(dossierId, coordinates) {
return $.ajax({
method: 'post',
url: '/users/dossiers/' + dossier_id + '/carte/cadastre',
data: {coordinates: JSON.stringify(coordinates)},
dataType: 'json',
async: false
}).done(function (data) {
cadastre = data
});
return cadastre['cadastres'];
url: `/users/dossiers/${dossierId}/carte/cadastre`,
data: { coordinates: JSON.stringify(coordinates) },
dataType: 'json'
}).then(({ cadastres }) => cadastres);
}
function display_cadastre(cadastre_array) {
if (!cadastre_active())
return;
let cadastreItems;
$("#cadastre.list ul").html('');
new_cadastreLayer();
export function displayCadastre(map, cadastres) {
if (!cadastreActive()) return;
if (cadastre_array.length == 1 && cadastre_array[0]['zoom_error'])
$("#cadastre.list ul").html('<li><b>Merci de dessiner une surface plus petite afin de récupérer les parcelles cadastrales.</b></li>');
$('#cadastre.list ul').html('');
newCadastreLayer(map);
else if (cadastre_array.length > 0) {
cadastre_array.forEach(function (cadastre) {
$("#cadastre.list ul").append('<li> Parcelle nº ' + cadastre.numero + ' - Feuille ' + cadastre.code_arr + ' ' + cadastre.section + ' ' + cadastre.feuille+ '</li>');
if (cadastres.length == 1 && cadastres[0]['zoom_error']) {
$('#cadastre.list ul').html(
'<li><b>Merci de dessiner une surface plus petite afin de récupérer les parcelles cadastrales.</b></li>'
);
} else if (cadastres.length > 0) {
cadastres.forEach(function(cadastre) {
$('#cadastre.list ul').append(
'<li> Parcelle nº ' +
cadastre.numero +
' - Feuille ' +
cadastre.code_arr +
' ' +
cadastre.section +
' ' +
cadastre.feuille +
'</li>'
);
cadastreItems.addData(cadastre.geometry);
});
@ -45,15 +50,16 @@ function display_cadastre(cadastre_array) {
color: 'white',
dashArray: '3',
fillOpacity: 0.7
})
});
} else {
$('#cadastre.list ul').html('<li>AUCUN</li>');
}
else
$("#cadastre.list ul").html('<li>AUCUN</li>');
}
function new_cadastreLayer() {
if (typeof cadastreItems != 'undefined')
function newCadastreLayer(map) {
if (cadastreItems) {
map.removeLayer(cadastreItems);
}
cadastreItems = new L.GeoJSON();
cadastreItems.addTo(map);

View file

@ -1,39 +1,30 @@
function qp_active() {
return $("#map.qp").length > 0
import L from 'leaflet';
import $ from 'jquery';
export function qpActive() {
return $('#map.qp').length > 0;
}
function get_qp(coordinates) {
if (!qp_active())
return;
var qp;
$.ajax({
export function getQP(dossierId, coordinates) {
return $.ajax({
method: 'post',
url: '/users/dossiers/' + dossier_id + '/carte/qp',
data: {coordinates: JSON.stringify(coordinates)},
dataType: 'json',
async: false
}).done(function (data) {
qp = data
});
return qp['quartier_prioritaires'];
url: `/users/dossiers/${dossierId}/carte/qp`,
data: { coordinates: JSON.stringify(coordinates) },
dataType: 'json'
}).done(({ quartier_prioritaires }) => values(quartier_prioritaires));
}
function display_qp(qp_list) {
if (!qp_active())
return;
let qpItems;
qp_array = jsObject_to_array(qp_list);
export function displayQP(map, qps) {
if (!qpActive()) return;
$("#qp.list ul").html('');
$('#qp.list ul').html('');
newQPLayer(map);
new_qpLayer();
if (qp_array.length > 0) {
qp_array.forEach(function (qp) {
$("#qp.list ul").append('<li>' + qp.commune + ' : ' + qp.nom + '</li>');
if (qps.length > 0) {
qps.forEach(function(qp) {
$('#qp.list ul').append('<li>' + qp.commune + ' : ' + qp.nom + '</li>');
qpItems.addData(qp.geometry);
});
@ -45,16 +36,21 @@ function display_qp(qp_list) {
color: 'white',
dashArray: '3',
fillOpacity: 0.7
})
});
} else {
$('#qp.list ul').html('<li>AUCUN</li>');
}
else
$("#qp.list ul").html('<li>AUCUN</li>');
}
function new_qpLayer() {
if (typeof qpItems != 'undefined')
function newQPLayer(map) {
if (qpItems) {
map.removeLayer(qpItems);
}
qpItems = new L.GeoJSON();
qpItems.addTo(map);
}
function values(obj) {
return Object.keys(obj).map(v => obj[v]);
}

View file

@ -11,6 +11,8 @@ import '../shared/autocomplete';
import '../shared/remote-input';
import '../shared/franceconnect';
import '../old_design/carto';
// Start Rails helpers
Rails.start();
Turbolinks.start();

View file

@ -0,0 +1,5 @@
const LON = '2.428462';
const LAT = '46.538192';
const DEFAULT_POSITION = { lon: LON, lat: LAT, zoom: 5 };
export { DEFAULT_POSITION, LAT, LON };

View file

@ -1,5 +1,6 @@
:javascript
var dossier_id = #{dossier.id};
addEventListener('turbolinks:load', function() {
initCarto();
DATA.push({
carto: {
dossierId: #{dossier.id}
}
});

View file

@ -1,5 +1,6 @@
#carte-page.row
.col-md-12.col-lg-12#map{ class: dossier.procedure.module_api_carto.classes }
.col-md-12.col-lg-12
#map{ class: dossier.procedure.module_api_carto.classes }
- if dossier.procedure.module_api_carto.quartiers_prioritaires
.col-md-9.col-lg-9#qp.col-md-3.col-lg-3.list