Remove legacy carto

This commit is contained in:
Paul Chavard 2020-05-14 11:21:33 +02:00
parent c4c1c971ca
commit 901b6e23a8
17 changed files with 10 additions and 572 deletions

View file

@ -1,45 +1,6 @@
class Champs::CarteController < ApplicationController
before_action :authenticate_logged_user!
ERROR_GEO_JSON = ''
def show
@selector = ".carte-#{params[:position]}"
feature_collection = if params[:dossier].key?(:champs_attributes)
params[:dossier][:champs_attributes][params[:position]][:value]
else
params[:dossier][:champs_private_attributes][params[:position]][:value]
end
@champ = if params[:champ_id].present?
policy_scope(Champ).find(params[:champ_id])
else
policy_scope(TypeDeChamp).find(params[:type_de_champ_id]).champ.build
end
geo_areas = []
if feature_collection == ERROR_GEO_JSON
@error = true
else
feature_collection = JSON.parse(feature_collection, symbolize_names: true)
if @champ.cadastres?
populate_cadastres(feature_collection)
end
geo_areas = GeoArea.from_feature_collection(feature_collection)
end
if @champ.persisted?
@champ.update(value: nil, geo_areas: geo_areas)
end
rescue ApiCarto::API::ResourceNotFound
flash.alert = 'Les données cartographiques sont temporairement indisponibles. Réessayez dans un instant.'
response.status = 503
end
def index
@selector = ".carte-#{params[:champ_id]}"
@champ = policy_scope(Champ).find(params[:champ_id])
@ -90,26 +51,6 @@ class Champs::CarteController < ApplicationController
private
def populate_cadastres(feature_collection)
coordinates = feature_collection[:features].filter do |feature|
feature[:geometry][:type] == 'Polygon'
end.map do |feature|
feature[:geometry][:coordinates][0].map { |(lng, lat)| { 'lng' => lng, 'lat' => lat } }
end
if coordinates.present?
cadastres = ApiCartoService.generate_cadastre(coordinates)
feature_collection[:features] += cadastres.map do |cadastre|
{
type: 'Feature',
geometry: cadastre.delete(:geometry),
properties: cadastre.merge(source: GeoArea.sources.fetch(:cadastre))
}
end
end
end
def params_feature
params[:feature]
end

View file

@ -4,12 +4,6 @@ module ChampHelper
!types_without_label.include?(champ.type_champ)
end
def geo_data(champ)
# rubocop:disable Rails/OutputSafety
raw(champ.to_render_data.to_json)
# rubocop:enable Rails/OutputSafety
end
def champ_carte_params(champ)
if champ.persisted?
{ champ_id: champ.id }

View file

@ -1,34 +0,0 @@
async function initialize() {
const elements = document.querySelectorAll('.carte');
if (elements.length) {
for (let element of elements) {
loadAndDrawMap(element);
}
}
}
async function loadAndDrawMap(element) {
const data = JSON.parse(element.dataset.geo);
const editable = element.classList.contains('edit');
if (editable) {
const { drawEditableMap } = await import('../../shared/carte-editor');
drawEditableMap(element, data);
}
}
async function loadAndRedrawMap(element, data) {
const { redrawMap } = await import('../../shared/carte-editor');
redrawMap(element, data);
}
addEventListener('DOMContentLoaded', initialize);
addEventListener('carte:update', ({ detail: { selector, data } }) => {
const element = document.querySelector(selector);
loadAndRedrawMap(element, data);
});

View file

@ -24,7 +24,6 @@ import '../new_design/support';
import '../new_design/dossiers/auto-save';
import '../new_design/dossiers/auto-upload';
import '../new_design/champs/carte';
import '../new_design/champs/linked-drop-down-list';
import '../new_design/champs/repetition';

View file

@ -1,220 +0,0 @@
import L from 'leaflet';
import FreeDraw from 'leaflet-freedraw';
import area from '@turf/area';
import { fire, delegate } from '@utils';
import $ from 'jquery';
import createFeatureCollection from './create-feature-collection';
const MAPS = new WeakMap();
export function drawEditableMap(element, data) {
const map = initMap(element, data);
drawCadastre(map, data);
drawQuartiersPrioritaires(map, data);
drawParcellesAgricoles(map, data);
drawUserSelectionEditor(map, data);
const input = element.parentElement.querySelector('input[data-remote]');
addFreeDrawEvents(map, input);
}
export function redrawMap(element, data) {
const map = initMap(element, data);
clearLayers(map);
drawCadastre(map, data);
drawQuartiersPrioritaires(map, data);
drawParcellesAgricoles(map, data);
bringToFrontUserSelection(map);
}
function initMap(element, { position }) {
if (MAPS.has(element)) {
return MAPS.get(element);
} else {
const map = L.map(element, {
scrollWheelZoom: false
}).setView([position.lat, position.lon], 18);
const loadTilesLayer = process.env.RAILS_ENV != 'test';
if (loadTilesLayer) {
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution:
'&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
}
const freeDraw = new FreeDraw({
mode: FreeDraw.NONE,
smoothFactor: 4,
mergePolygons: false
});
map.addLayer(freeDraw);
map.freeDraw = freeDraw;
MAPS.set(element, map);
return map;
}
}
function toLatLngs({ coordinates }) {
return coordinates.map((polygon) =>
polygon[0].map((point) => L.GeoJSON.coordsToLatLng(point))
);
}
function drawUserSelectionEditor(map, { selection }) {
if (selection) {
const geoJSON = L.geoJSON(selection);
for (let polygon of toLatLngs(selection)) {
map.freeDraw.create(polygon);
}
map.fitBounds(geoJSON.getBounds());
}
}
export function addFreeDrawEvents(map, selector) {
const input = findInput(selector);
map.freeDraw.on('markers', ({ latLngs }) => {
if (latLngs.length === 0) {
input.value = EMPTY_GEO_JSON;
} else {
const featureCollection = createFeatureCollection(latLngs);
if (area(featureCollection) < 300000) {
input.value = JSON.stringify(featureCollection);
} else {
input.value = ERROR_GEO_JSON;
}
}
fire(input, 'change');
});
}
function drawCadastre(map, { cadastres }) {
drawLayer(map, cadastres, CADASTRE_POLYGON_STYLE);
}
function drawQuartiersPrioritaires(map, { quartiersPrioritaires }) {
drawLayer(map, quartiersPrioritaires, QP_POLYGON_STYLE);
}
function drawParcellesAgricoles(map, { parcellesAgricoles }) {
drawLayer(map, parcellesAgricoles, RPG_POLYGON_STYLE);
}
function getCurrentMap(element) {
if (!element.matches('.carte')) {
const closestCarteElement = element.closest('.carte');
const closestToolbarElement = element.closest('.toolbar');
element = closestCarteElement
? closestCarteElement
: closestToolbarElement.parentElement.querySelector('.carte');
}
if (MAPS.has(element)) {
return MAPS.get(element);
}
}
const EMPTY_GEO_JSON = '{ "type": "FeatureCollection", "features": [] }';
const ERROR_GEO_JSON = '';
function findInput(selector) {
return typeof selector === 'string'
? document.querySelector(selector)
: selector;
}
function clearLayers(map) {
map.eachLayer((layer) => {
if (layer instanceof L.GeoJSON) {
map.removeLayer(layer);
}
});
}
function bringToFrontUserSelection(map) {
for (let layer of map.freeDraw.all()) {
layer.bringToFront();
}
}
function drawLayer(map, data, style) {
if (Array.isArray(data) && data.length > 0) {
const layer = new L.GeoJSON(undefined, {
interactive: false,
style
});
for (let { geometry } of data) {
layer.addData(geometry);
}
layer.addTo(map);
}
}
const POLYGON_STYLE = {
weight: 2,
opacity: 0.3,
color: 'white',
dashArray: '3',
fillOpacity: 0.7
};
const CADASTRE_POLYGON_STYLE = Object.assign({}, POLYGON_STYLE, {
fillColor: '#8a6d3b'
});
const QP_POLYGON_STYLE = Object.assign({}, POLYGON_STYLE, {
fillColor: '#31708f'
});
const RPG_POLYGON_STYLE = Object.assign({}, POLYGON_STYLE, {
fillColor: '#31708f'
});
delegate('click', '.carte.edit', (event) => {
const map = getCurrentMap(event.target);
if (map) {
const isPath = event.target.matches('.leaflet-container g path');
if (isPath) {
setTimeout(() => {
map.freeDraw.mode(FreeDraw.EDIT | FreeDraw.DELETE);
}, 50);
} else {
map.freeDraw.mode(FreeDraw.NONE);
}
}
});
delegate('click', '.toolbar .new-area', (event) => {
event.preventDefault();
const map = getCurrentMap(event.target);
if (map) {
map.freeDraw.mode(FreeDraw.CREATE);
}
});
$(document).on('select2:select', 'select[data-address]', (event) => {
const map = getCurrentMap(event.target);
const { geometry } = event.params.data;
if (map && geometry && geometry.type === 'Point') {
const [lon, lat] = geometry.coordinates;
map.setView(new L.LatLng(lat, lon), 14);
}
});

View file

@ -1,19 +0,0 @@
export default function createFeatureCollection(latLngs) {
return {
type: 'FeatureCollection',
features: latLngs.map(featurePolygonLatLngs)
};
}
function featurePolygonLatLngs(latLngs) {
return {
type: 'Feature',
properties: {
source: 'selection_utilisateur'
},
geometry: {
type: 'Polygon',
coordinates: [latLngs.map(({ lng, lat }) => [lng, lat])]
}
};
}

View file

@ -80,10 +80,6 @@ class Champs::CarteChamp < Champ
}
end
def has_cadastres?
cadastres? ? true : false
end
def geometry?
geo_areas.present?
end
@ -98,16 +94,6 @@ class Champs::CarteChamp < Champ
end
end
def to_render_data
{
position: position,
selection: selection_utilisateur_legacy_geometry,
quartiersPrioritaires: quartiers_prioritaires? ? quartiers_prioritaires.as_json(except: :properties) : [],
cadastres: cadastres? ? cadastres.as_json(except: :properties) : [],
parcellesAgricoles: parcelles_agricoles? ? parcelles_agricoles.as_json(except: :properties) : []
}
end
def for_api
nil
end

View file

@ -2,7 +2,7 @@
<%= render_to_element("#{@selector} + .geo-areas",
partial: 'shared/champs/carte/geo_areas',
locals: { champ: @champ, error: @error }) %>
locals: { champ: @champ }) %>
<% if @update_cadastres %>
<%= fire_event('cadastres:update', { featureCollection: @champ.to_feature_collection }.to_json) %>

View file

@ -1,7 +0,0 @@
<%= render_flash(timeout: 5000, fixed: true) %>
<%= render_to_element("#{@selector} + .geo-areas",
partial: 'shared/champs/carte/geo_areas',
locals: { champ: @champ, error: @error }) %>
<%= fire_event('carte:update', { selector: @selector, data: @champ.to_render_data }.to_json) %>

View file

@ -8,9 +8,7 @@
- if champ.quartiers_prioritaires?
.areas-title Quartiers prioritaires
.areas
- if error.present?
.error Merci de dessiner une surface plus petite afin de récupérer les quartiers prioritaires.
- elsif !champ.geometry?
- if !champ.geometry?
Aucune zone tracée
- elsif champ.quartiers_prioritaires.blank?
= t('errors.messages.quartiers_prioritaires_empty', count: champ.selections_utilisateur.size)
@ -22,9 +20,7 @@
- if champ.cadastres?
.areas-title Parcelles cadastrales
.areas
- if error.present?
.error Merci de dessiner une surface plus petite afin de récupérer les parcelles cadastrales.
- elsif !champ.geometry?
- if !champ.geometry?
Aucune zone tracée
- elsif champ.cadastres.blank?
= t('errors.messages.cadastres_empty', count: champ.selections_utilisateur.size)
@ -36,9 +32,7 @@
- if champ.parcelles_agricoles?
.areas-title Parcelles agricoles (RPG)
.areas
- if error.present?
.error Merci de dessiner une surface plus petite afin de récupérer les parcelles agricoles.
- elsif !champ.geometry?
- if !champ.geometry?
Aucune zone tracée
- elsif champ.parcelles_agricoles.blank?
= t('errors.messages.parcelles_agricoles_empty', count: champ.selections_utilisateur.size)

View file

@ -1,4 +1,4 @@
- if champ.geometry?
= react_component("MapReader", { featureCollection: champ.to_feature_collection } )
.geo-areas
= render partial: 'shared/champs/carte/geo_areas', locals: { champ: champ, error: false }
= render partial: 'shared/champs/carte/geo_areas', locals: { champ: champ }

View file

@ -1,14 +1,5 @@
- if feature_enabled?(:new_map_editor)
- preview = !champ.persisted?
= react_component("MapEditor", { featureCollection: champ.to_feature_collection, hasCadastres: champ.has_cadastres?, url: champs_carte_features_path(preview ? 'preview' : champ), preview: preview }, class: "carte-#{champ.id}")
- else
.toolbar
%button.button.primary.new-area Ajouter une zone
%select.select2.adresse{ data: { address: true }, placeholder: 'Saisissez une adresse ou positionner la carte' }
.carte.edit{ data: { geo: geo_data(champ) }, class: "carte-#{form.index}" }
= form.hidden_field :value,
data: { remote: true, feature_collection_id: champ.stable_id, url: champs_carte_path(form.index), params: champ_carte_params(champ).to_query, method: 'post' }
- preview = !champ.persisted?
= react_component("MapEditor", { featureCollection: champ.to_feature_collection, url: champs_carte_features_path(preview ? 'preview' : champ), preview: preview, hasCadastres: !!champ.cadastres? }, class: "carte-#{champ.id}")
.geo-areas
= render partial: 'shared/champs/carte/geo_areas', locals: { champ: champ, error: false }
= render partial: 'shared/champs/carte/geo_areas', locals: { champ: champ }