This commit is contained in:
Tykayn 2025-06-06 13:26:44 +02:00 committed by tykayn
parent a17fd9c232
commit 8bce5fe21c
14 changed files with 628 additions and 634 deletions

View file

@ -0,0 +1,21 @@
<div class="container">
<h1>Édition</h1>
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-body">
<h5 class="card-title">Carte</h5>
<div id="map" style="height: 600px;"></div>
<div class="mt-3">
<button id="openInJOSM" class="btn btn-primary">Ouvrir dans JOSM</button>
<a href="#" id="viewInPanoramax" class="btn btn-secondary" target="_blank">Voir dans Panoramax</a>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="{{ asset('js/app.js') }}"></script>

View file

@ -25,7 +25,7 @@ commerces existants déjà en base: {{ commerces|length }}
</p>
{# {{ dump(commerces[0]) }} #}
<table class="table table-striped">
<table class="table table-striped js-sort-table">
{% include 'admin/stats/table-head.html.twig' %}
<tbody>

View file

@ -86,7 +86,7 @@
</a>
</div>
</div>
<table class="table table-bordered table-striped table-hover table-responsive">
<table class="table table-bordered table-striped table-hover table-responsive js-sort-table">
{% include 'admin/stats/table-head.html.twig' %}
<tbody>
{% for commerce in stats.places %}
@ -103,21 +103,20 @@
</div>
</div>
<!-- Bouton caché pour JOSM -->
<a id="josmButton" style="display: none;"></a>
<script src='{{ asset('js/maplibre/maplibre-gl.js') }}'></script>
<script src='{{ asset('js/turf/turf.min.js') }}'></script>
<script src="{{ asset('js/chartjs/chart.umd.js') }}"></script>
<script src="{{ asset('js/app.js') }}"></script>
<script>
const request = `{{query_places|raw}}`;
const zip_code = `{{stats.zone}}`;
let mapElements = [];
let map_is_loaded=false;
let map_is_loaded = false;
let features = [];
const map = new maplibregl.Map({
container: 'map',
style: 'https://api.maptiler.com/maps/streets-v2/style.json?key={{ maptiler_token }}',
center: [2.3488, 48.8534],
zoom: 12
});
function getCompletionColor(completion) {
if (completion === undefined || completion === null) {
@ -239,76 +238,104 @@ const map = new maplibregl.Map({
}
});
}
async function fetchland() {
// Requête pour obtenir le contour administratif
const boundaryQuery = `[out:json][timeout:25];
area["ref:INSEE"="${zip_code}"]->.searchArea;
(
relation["boundary"="postal_code"]["ref:INSEE"="${zip_code}"](area.searchArea);
);
out body;
>;
out skel qt;`;
const encodedBoundaryRequest = encodeURIComponent(boundaryQuery);
const boundaryResponse = await fetch(`https://overpass-api.de/api/interpreter?data=${encodedBoundaryRequest}`);
const boundaryData = await boundaryResponse.json();
const encodedRequest = encodeURIComponent(request);
const overpassUrl = `https://overpass-api.de/api/interpreter?data=${encodedRequest}`;
const response = await fetch(overpassUrl);
const data = await response.json();
map.on('load', () => {
map_is_loaded=true;
console.log('map load...');
// Ajouter le contour administratif
if (boundaryData.elements && boundaryData.elements.length > 0) {
const boundary = boundaryData.elements[0];
if (boundary.members) {
const coordinates = boundary.members.map(member => {
if (member.type === 'node') {
return [member.lon, member.lat];
}
}).filter(coord => coord);
map.addSource('boundary', {
'type': 'geojson',
'data': {
'type': 'Feature',
'geometry': {
'type': 'Polygon',
'coordinates': [coordinates]
}
}
});
map.addLayer({
'id': 'boundary-layer',
'type': 'fill',
'source': 'boundary',
'paint': {
'fill-color': '#088',
'fill-opacity': 0.1,
'fill-outline-color': '#000'
}
});
}
}else{
console.log('pas de contour administratif trouvé');
async function loadPlaces(map) {
map_is_loaded = false;
try {
const response = await fetch('https://overpass-api.de/api/interpreter', {
method: 'POST',
body: request
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
console.log('map chargé',data.elements);
const data = await response.json();
console.log('Lieux chargés:', data.elements);
mapElements = data.elements;
map_is_loaded = true;
// Créer le graphique de distribution
createCompletionChart(data.elements);
document.getElementById('maploader').classList.add('d-none');
// Mettre à jour les cercles
features = [];
data.elements.forEach(element => {
const lat = element.lat || (element.center && element.center.lat);
const lon = element.lon || (element.center && element.center.lon);
if (lat && lon) {
const completion = calculateCompletion(element);
const color = getCompletionColor(completion);
// Créer un cercle de 20 mètres de rayon (plus petit)
const circle = turf.circle([lon, lat], 0.04, { steps: 64, units: 'kilometers' });
circle.properties = {
color: color,
completion: completion,
name: element.tags?.name || 'Sans nom',
popupContent: createPopupContent(element),
center: [lon, lat] // Stocker le centre comme un tableau [lon, lat]
};
features.push(circle);
}
});
// Mettre à jour la source des cercles
map.getSource('completion-circles').setData({
'type': 'FeatureCollection',
'features': features
});
// Calculer les bounds pour tous les points
const points = features.map(f => f.properties.center);
if (points.length > 0) {
const bounds = new maplibregl.LngLatBounds(points[0], points[0]);
points.forEach(point => bounds.extend(point));
// Vérifier que les bounds sont valides avant de les utiliser
if (bounds?._sw && bounds?._ne) {
map.fitBounds(bounds, {
padding: 50,
maxZoom: 15
});
} else {
console.warn('Bounds invalides, utilisation des coordonnées par défaut');
}
}
document.getElementById('maploader').classList.add('d-none');
} catch (error) {
console.error('Erreur lors du chargement des lieux:', error);
document.getElementById('maploader').classList.add('d-none');
}
}
function openInJOSM() {
const selectedElements = document.querySelectorAll('input[type="checkbox"]:checked');
if (selectedElements.length === 0) {
alert('Veuillez sélectionner au moins un élément');
return;
}
const osmElements = Array.from(selectedElements).map(checkbox => {
return JSON.parse(checkbox.value);
});
window.openInJOSM(map, map_is_loaded, osmElements);
}
document.addEventListener('DOMContentLoaded', function() {
console.log('DOMContentLoaded');
const map = new maplibregl.Map({
container: 'map',
style: 'https://api.maptiler.com/maps/streets-v2/style.json?key={{ maptiler_token }}',
center: [2.3488, 48.8534],
zoom: 12
});
document.getElementById('openInJOSM').addEventListener('click', openInJOSM);
map.on('load', () => {
// Créer une source pour les cercles
map.addSource('completion-circles', {
'type': 'geojson',
@ -341,57 +368,6 @@ out skel qt;`;
}
});
const features = [];
data.elements.forEach(element => {
const lat = element.lat || (element.center && element.center.lat);
const lon = element.lon || (element.center && element.center.lon);
if (lat && lon) {
const completion = calculateCompletion(element);
const color = getCompletionColor(completion);
// Créer un cercle de 20 mètres de rayon (plus petit)
const circle = turf.circle([lon, lat], 0.04, { steps: 64, units: 'kilometers' });
circle.properties = {
color: color,
completion: completion,
name: element.tags?.name || 'Sans nom',
popupContent: createPopupContent(element),
center: [lon, lat] // Stocker le centre comme un tableau [lon, lat]
};
features.push(circle);
}
});
// Mettre à jour la source des cercles
map.getSource('completion-circles').setData({
'type': 'FeatureCollection',
'features': features
});
// Fonction pour recalculer les cercles en fonction du zoom
function updateCircles() {
const zoom = map.getZoom();
const newFeatures = [];
features.forEach(feature => {
// Ajuster la taille du cercle en fonction du zoom
// Plus le zoom est élevé, plus le cercle est petit
const radius = 0.02 / Math.pow(1.5, zoom - 12); // 12 est le niveau de zoom de référence
const newCircle = turf.circle(feature.properties.center, radius, { steps: 64, units: 'kilometers' });
newCircle.properties = feature.properties;
newFeatures.push(newCircle);
});
map.getSource('completion-circles').setData({
'type': 'FeatureCollection',
'features': newFeatures
});
}
// Mettre à jour les cercles lors du zoom
map.on('zoom', updateCircles);
// Ajouter les popups sur les cercles
map.on('click', 'completion-circles', (e) => {
const properties = e.features[0].properties;
@ -410,104 +386,14 @@ out skel qt;`;
map.on('mouseleave', 'completion-circles', () => {
map.getCanvas().style.cursor = '';
});
// Charger les lieux
loadPlaces(map);
});
// Calculer les limites (bounds) à partir des marqueurs
const bounds = new maplibregl.LngLatBounds();
data.elements.forEach(element => {
if (element.lat && element.lon) {
bounds.extend([element.lon, element.lat]);
}
});
// Centrer et zoomer la carte pour inclure tous les marqueurs
if (!bounds.isEmpty()) {
map.fitBounds(bounds, {
padding: 50 // Ajoute une marge autour des marqueurs
});
}
}
function openInJOSM() {
if (mapElements.length === 0) {
alert('Aucun élément à ouvrir dans JOSM');
return;
}
if (!map_is_loaded) {
alert('La carte n\'est pas encore chargée, veuillez patienter');
return;
}
const nodeIds = [];
const wayIds = [];
const relationIds = [];
mapElements.forEach(element => {
switch(element.type) {
case 'node':
nodeIds.push(element.id);
break;
case 'way':
wayIds.push(element.id);
break;
case 'relation':
relationIds.push(element.id);
break;
}
});
// Obtenir les coordonnées du viewport actuel
const center = map.getCenter();
const zoom = map.getZoom();
const width = map.getCanvas().width;
const height = map.getCanvas().height;
// Calculer les limites en utilisant les coordonnées du centre et le zoom
const west = center.lng - (360 / Math.pow(2, zoom + 1)) * (width / 256);
const east = center.lng + (360 / Math.pow(2, zoom + 1)) * (width / 256);
const north = center.lat + (180 / Math.pow(2, zoom + 1)) * (height / 256);
const south = center.lat - (180 / Math.pow(2, zoom + 1)) * (height / 256);
let josmUrl = 'http://localhost:8111/load_and_zoom?';
const params = [];
if (nodeIds.length > 0) {
params.push(`node${nodeIds.join(',')}`);
}
if (wayIds.length > 0) {
params.push(`way${wayIds.join(',')}`);
}
if (relationIds.length > 0) {
params.push(`relation${relationIds.join(',')}`);
}
// Ajouter la bounding box calculée
params.push(`left=${west}&right=${east}&top=${north}&bottom=${south}`);
josmUrl += params.join('&');
window.open(josmUrl);
}
document.addEventListener('DOMContentLoaded', function() {
console.log('DOMContentLoaded');
const headers = document.querySelectorAll('th');
headers.forEach(header => {
const text = header.textContent;
const match = text.match(/\((\d+)\s*\/\s*(\d+)\)/);
if (match) {
const [_, completed, total] = match;
const ratio = completed / total;
const alpha = ratio.toFixed(2);
header.style.backgroundColor = `rgba(154, 205, 50, ${alpha})`;
}
});
document.getElementById('openInJOSM').addEventListener('click', openInJOSM);
fetchland();
sortTable();
colorHeadingTable();
});
</script>
{% endblock %}

View file

@ -107,11 +107,11 @@
{% block javascripts %}
{{ encore_entry_script_tags('app') }}
<script src="{{ asset('js/bootstrap/bootstrap.bundle.min.js') }}"></script>
<script src='{{ asset('js/maplibre/maplibre-gl.js') }}'></script>
<script src="{{ asset('js/sort-table/sort-table.js') }}"></script>
<!-- Script pour le tri automatique des tableaux -->
<script src="{{ asset('js/bootstrap/Sortable.min.js') }}"></script>
{# <script src="{{ asset('js/bootstrap/Sortable.min.js') }}"></script> #}
<script src="{{ asset('js/qrcode/qrcode.min.js') }}"></script>
<script>
new QRCode(document.getElementById('qrcode'), {

View file

@ -18,7 +18,7 @@
<h1>Commerces fermés</h1>
<p>Voici la liste des commerces fermés :</p>
<div class="table-responsive">
<table class="table table-striped">
<table class="table table-striped js-sort-table">
<thead>
<tr>
<th>Nom du commerce</th>

View file

@ -122,12 +122,12 @@
}
// Créer une carte des villes avec les codes postaux
{# let map = new maplibregl.Map({
let map = new maplibregl.Map({
container: 'mapDashboard',
style: 'https://api.maptiler.com/maps/basic-v2/style.json?key={{ maptiler_token }}',
center: [2.3488, 48.8534], // Paris
zoom: 10
}); #}
});
// Fonction pour obtenir la couleur selon le pourcentage
function getColorFromPercent(percent) {
@ -190,7 +190,7 @@ out skel qt;`;
{# <div id="mapDashboard"></div> #}
<table class="table table-hover table-striped table-responsive">
<table class="table table-hover table-striped table-responsive js-sort-table">
<thead>
<tr>
<th>Zone</th>

View file

@ -135,12 +135,12 @@
<span class="last-modification">{{ 'display.last_modification'|trans }}: {{ commerce_overpass['@attributes'].timestamp }}</span>,
<strong>{{ 'display.days_ago'|trans({'%days%': date(commerce_overpass['@attributes'].timestamp).diff(date()).days}) }}</strong>
{{ 'display.by'|trans }}
<a href="https://www.openstreetmap.org/user/{{ commerce_overpass['@attributes'].user }}" target="_blank">{{ commerce_overpass['@attributes'].user }}</a>
<a href="https://www.openstreetmap.org/user/{{ commerce_overpass['@attributes'].user }}" >{{ commerce_overpass['@attributes'].user }}</a>
</div>
<div class="lien-OpenStreetMap">
<a href="https://www.openstreetmap.org/{{commerce.osmKind}}/{{ commerce_overpass['@attributes'].id }}" target="_blank" class="btn btn-outline-secondary">
<a href="https://www.openstreetmap.org/{{commerce.osmKind}}/{{ commerce_overpass['@attributes'].id }}" class="btn btn-outline-secondary">
{{ 'display.view_on_osm'|trans }}
</a>
<button onclick="openInJOSM('{{commerce.osmKind}}', '{{ commerce_overpass['@attributes'].id }}')" class="btn btn-outline-secondary ms-2">
@ -183,14 +183,14 @@
<script>
function openInJOSM(type, id) {
const josmUrl = `http://localhost:8111/load_object?objects=${type}${id}`;
window.open(josmUrl, '_blank');
window.open(josmUrl);
}
function openInPanoramax() {
const center = map.getCenter();
const zoom = map.getZoom();
const panoramaxUrl = `https://api.panoramax.xyz/?focus=map&map=${zoom}/${center.lat}/${center.lng}`;
window.open(panoramaxUrl, '_blank');
window.open(panoramaxUrl);
}
{% if commerce is not empty and mapbox_token is not empty and maptiler_token is not empty and commerce_overpass['@attributes'].lon is defined and commerce_overpass['@attributes'].lat is defined %}

View file

@ -9,7 +9,7 @@
<div class="row">
<div class="col-12 col-md-6 ">
<h2>Lieux modifiés</h2>
<table class="table table-striped table-hover table-responsive">
<table class="table table-striped table-hover table-responsive js-sort-table">
<thead>
<tr>
<th>Nom</th>
@ -33,7 +33,7 @@
</div>
<div class="col-12 col-md-6 ">
<h2>Lieux affichés</h2>
<table class="table table-striped table-hover table-responsive">
<table class="table table-striped table-hover table-responsive js-sort-table">
<thead>
<tr>
<th>Nom</th>

View file

@ -5,7 +5,7 @@
{% block body %}
<div class="container">
<h1>Commerces avec une note</h1>
<table class="table table-striped">
<table class="table table-striped js-sort-table table-hover table-responsive">
<thead>
<tr>
<th>Nom</th>