File size: 28,984 Bytes
9debbd0 6ecea15 9debbd0 688ed55 9debbd0 688ed55 9debbd0 688ed55 9debbd0 688ed55 9debbd0 688ed55 9debbd0 688ed55 9debbd0 688ed55 9debbd0 688ed55 9debbd0 688ed55 9debbd0 688ed55 9debbd0 688ed55 9debbd0 688ed55 9debbd0 688ed55 9debbd0 6ecea15 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>DVF - Prix Immobiliers en France</title>
<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no">
<link href="https://unpkg.com/maplibre-gl@3.6.2/dist/maplibre-gl.css" rel="stylesheet">
<script src="https://unpkg.com/maplibre-gl@3.6.2/dist/maplibre-gl.js"></script>
<script src="https://unpkg.com/pmtiles@2.11.0/dist/index.js"></script>
<style>
body { margin: 0; padding: 0; }
#map { position: absolute; top: 0; bottom: 0; width: 100%; }
.map-overlay {
position: absolute;
background: rgba(255, 255, 255, 0.95);
border-radius: 8px;
padding: 15px;
box-shadow: 0 2px 10px rgba(0,0,0,0.15);
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
font-size: 13px;
}
#info {
top: 10px;
left: 10px;
min-width: 200px;
}
#info h3 {
margin: 0 0 10px 0;
font-size: 16px;
color: #333;
}
#info .stat {
margin: 5px 0;
color: #666;
}
#info .stat strong {
color: #333;
}
#legend {
bottom: 30px;
left: 10px;
padding: 10px 15px;
}
#legend h4 {
margin: 0 0 10px 0;
font-size: 14px;
}
.legend-scale {
display: flex;
height: 15px;
border-radius: 3px;
overflow: hidden;
}
.legend-scale div {
flex: 1;
}
.legend-labels {
display: flex;
justify-content: space-between;
margin-top: 5px;
font-size: 11px;
color: #666;
}
#controls {
top: 10px;
right: 10px;
}
#controls label {
display: block;
margin: 5px 0;
cursor: pointer;
}
#controls select {
width: 100%;
padding: 5px;
margin-top: 10px;
border-radius: 4px;
border: 1px solid #ccc;
}
#zoom-level {
position: absolute;
bottom: 30px;
right: 10px;
background: rgba(255,255,255,0.9);
padding: 5px 10px;
border-radius: 4px;
font-family: monospace;
font-size: 12px;
}
#top-cities {
top: 80px;
right: 10px;
max-width: 220px;
display: none;
}
#top-cities h4 {
margin: 0 0 10px 0;
font-size: 14px;
}
#top-cities ol {
margin: 0;
padding-left: 20px;
}
#top-cities li {
margin: 4px 0;
font-size: 12px;
}
#top-cities .city-name {
font-weight: 500;
}
#top-cities .city-stats {
color: #666;
font-size: 11px;
}
</style>
</head>
<body>
<div id="map"></div>
<div class="map-overlay" id="info">
<h3>Prix Immobiliers</h3>
<div id="hover-info">
<p style="color: #999;">Survolez une zone pour voir les prix</p>
</div>
</div>
<div class="map-overlay" id="legend">
<h4>Prix médian (€/m²)</h4>
<div class="legend-scale" id="legend-scale"></div>
<div class="legend-labels" id="legend-labels">
<span>1 500</span>
<span>2 500</span>
<span>3 500</span>
<span>5 000</span>
<span>8 000+</span>
</div>
<div style="margin-top: 8px; display: flex; align-items: center; font-size: 11px; color: #666;">
<span style="display: inline-block; width: 16px; height: 12px; background: #999999; border-radius: 2px; margin-right: 6px;"></span>
<span>Aucune transaction</span>
</div>
<div style="margin-top: 4px; display: flex; align-items: center; font-size: 11px; color: #666;">
<span style="display: inline-block; width: 16px; height: 12px; background: #cccccc; border-radius: 2px; margin-right: 6px;"></span>
<span>< 5 transactions</span>
</div>
<div id="current-level" style="margin-top: 8px; font-size: 11px; color: #999;">Niveau: Pays</div>
</div>
<div class="map-overlay" id="controls">
<strong>Type de bien</strong>
<select id="property-type">
<option value="all">Tous types</option>
<option value="maison">Maisons</option>
<option value="appartement">Appartements</option>
</select>
</div>
<div id="zoom-level">Zoom: <span id="zoom-value">5</span></div>
<div class="map-overlay" id="top-cities">
<h4>🏆 Top 10 Villes</h4>
<div id="top-cities-list"></div>
</div>
<script>
console.log('Script starting...');
console.log('pmtiles defined?', typeof pmtiles !== 'undefined');
console.log('maplibregl defined?', typeof maplibregl !== 'undefined');
// PMTiles protocol registration
let pmtilesAvailable = false;
try {
if (typeof pmtiles !== 'undefined' && typeof maplibregl !== 'undefined') {
const protocol = new pmtiles.Protocol();
maplibregl.addProtocol("pmtiles", protocol.tile);
pmtilesAvailable = true;
console.log('PMTiles protocol registered successfully');
} else {
console.log('PMTiles or MapLibre library not loaded');
}
} catch (e) {
console.error('PMTiles registration error:', e);
}
// Color palette (green to yellow to red)
const colors = ['#1a9850', '#a6d96a', '#ffdd00', '#f46d43', '#d73027'];
// Will be populated with actual min/max from data
const priceScales = {
country: null,
regions: null,
departments: null,
iris: null,
communes: null,
parcels: null
};
// Store loaded GeoJSON data
const geoData = {};
// Compute price scale from GeoJSON features with 5 stops
function computePriceScale(features, priceField, level = 'default') {
// Fixed scale from 1500 to 8000 €/m² for all levels
return [1500, 3125, 4750, 6375, 8000];
}
// Build legend gradient (static colors)
const legendScale = document.getElementById('legend-scale');
colors.forEach(color => {
const div = document.createElement('div');
div.style.backgroundColor = color;
legendScale.appendChild(div);
});
// Initialize map (MapLibre with free Carto basemap)
const map = new maplibregl.Map({
container: 'map',
style: 'https://basemaps.cartocdn.com/gl/positron-gl-style/style.json',
center: [2.3, 46.5], // Center of France
zoom: 4,
minZoom: 3,
maxZoom: 18
});
// Current property type filter
let currentPropertyType = 'all';
let currentLevel = 'country';
let topCitiesData = [];
function updateTopCitiesPanel() {
const countField = getCountField();
const priceField = getPriceField();
// Aggregate arrondissements for Paris, Lyon, Marseille
const aggregated = {};
const bigCities = {
'Paris': { pattern: /^Paris \d+e?r? Arrondissement$/i, code: '75' },
'Marseille': { pattern: /^Marseille \d+e?r? Arrondissement$/i, code: '13' },
'Lyon': { pattern: /^Lyon \d+e?r? Arrondissement$/i, code: '69' }
};
topCitiesData.forEach(f => {
const name = f.properties.nom_commune || f.properties.nom_commune_geo || '';
const count = f.properties[countField] || 0;
const price = f.properties[priceField];
if (count === 0) return;
// Check if it's an arrondissement of a big city
let aggregateName = null;
for (const [city, info] of Object.entries(bigCities)) {
if (info.pattern.test(name)) {
aggregateName = city;
break;
}
}
if (aggregateName) {
// Aggregate into big city
if (!aggregated[aggregateName]) {
aggregated[aggregateName] = { name: aggregateName, count: 0, priceSum: 0, priceCount: 0 };
}
aggregated[aggregateName].count += count;
if (price) {
aggregated[aggregateName].priceSum += price * count;
aggregated[aggregateName].priceCount += count;
}
} else {
// Regular commune
aggregated[name] = { name, count, priceSum: price ? price * count : 0, priceCount: price ? count : 0 };
}
});
// Convert to array and sort
const sorted = Object.values(aggregated)
.map(c => ({
name: c.name,
count: c.count,
price: c.priceCount > 0 ? c.priceSum / c.priceCount : null
}))
.sort((a, b) => b.count - a.count)
.slice(0, 10);
const listHtml = sorted.map((c, i) => {
const priceStr = c.price ? Math.round(c.price).toLocaleString('fr-FR') + ' €/m²' : 'N/A';
return `<div style="margin: 6px 0;"><span class="city-name">${i+1}. ${c.name}</span><br><span class="city-stats">${c.count.toLocaleString('fr-FR')} transactions • ${priceStr}</span></div>`;
}).join('');
document.getElementById('top-cities-list').innerHTML = listHtml;
}
function showTopCities(show) {
document.getElementById('top-cities').style.display = show ? 'block' : 'none';
}
function getPriceField() {
switch(currentPropertyType) {
case 'maison': return 'prix_m2_maison_median';
case 'appartement': return 'prix_m2_appart_median';
default: return 'prix_m2_median';
}
}
function getCountField() {
switch(currentPropertyType) {
case 'maison': return 'nb_maisons';
case 'appartement': return 'nb_appartements';
default: return 'nb_transactions';
}
}
// Format price for display
function formatPrice(price) {
if (price === null || price === undefined) return 'N/A';
return Math.round(price).toLocaleString('fr-FR') + ' €/m²';
}
function formatCount(count) {
if (count === null || count === undefined) return 'N/A';
return count.toLocaleString('fr-FR');
}
// Update hover info panel
function updateInfo(properties, level) {
const priceField = getPriceField();
const countField = getCountField();
let name = '';
if (level === 'country') {
name = properties.name || 'France';
} else if (level === 'regions') {
name = properties.nom_region || properties.nom_region_geo || 'Région';
} else if (level === 'departments') {
name = properties.nom_departement || 'Département';
} else if (level === 'iris') {
const irisName = properties.nom_iris || '';
const communeName = properties.nom_commune_iris || '';
const irisCode = properties.code_iris || '';
// If IRIS name equals commune name, show code for distinction
if (irisName === communeName && irisCode) {
name = `IRIS ${irisCode} (${communeName})`;
} else if (irisName) {
name = communeName && irisName !== communeName ? `${irisName} (${communeName})` : irisName;
} else {
name = irisCode ? `IRIS ${irisCode}` : 'IRIS';
}
} else if (level === 'communes') {
name = properties.nom_commune || properties.nom_commune_geo || 'Commune';
} else if (level === 'parcels') {
const parcelId = properties.id_parcelle_unique || properties.id || '';
const commune = properties.nom_commune || '';
name = commune ? `Parcelle ${parcelId} (${commune})` : `Parcelle ${parcelId}`;
}
const price = properties[priceField];
const priceMean = properties[priceField.replace('median', 'mean')];
const count = properties[countField];
const priceQ25 = properties[priceField.replace('median', 'q25')];
const priceQ75 = properties[priceField.replace('median', 'q75')];
const noData = (count || 0) === 0;
const insufficientData = (count || 0) > 0 && (count || 0) < 5;
let dataNote = '';
if (noData) {
dataNote = '<div class="stat" style="color: #888; font-style: italic;">⛔ Aucune transaction</div>';
} else if (insufficientData) {
dataNote = '<div class="stat" style="color: #999; font-style: italic;">⚠️ Données insuffisantes (<5 transactions)</div>';
}
document.getElementById('hover-info').innerHTML = `
<div class="stat"><strong>${name}</strong></div>
${dataNote}
<div class="stat">Prix médian: <strong>${noData ? 'N/A' : formatPrice(price)}</strong></div>
<div class="stat">Prix moyen: ${noData ? 'N/A' : formatPrice(priceMean)}</div>
<div class="stat">Fourchette: ${noData ? 'N/A' : formatPrice(priceQ25) + ' - ' + formatPrice(priceQ75)}</div>
<div class="stat">Transactions: <strong>${formatCount(count)}</strong></div>
`;
}
function resetInfo() {
document.getElementById('hover-info').innerHTML =
'<p style="color: #999;">Survolez une zone pour voir les prix</p>';
}
// Build fill-color expression for a layer with specific scale
// Shows darker gray for no data, lighter gray for <5 transactions (except parcels)
function buildFillColor(level) {
const priceField = getPriceField();
const countField = getCountField();
// Default scale if not computed yet (parcels use communes scale as fallback)
const defaultScale = [1500, 3125, 4750, 6375, 8000];
const scale = priceScales[level] || priceScales['communes'] || defaultScale;
// Build interpolation stops: [price1, color1, price2, color2, ...]
const stops = [];
for (let i = 0; i < scale.length; i++) {
stops.push(scale[i], colors[i]);
}
// For parcels: just use price-based coloring (each parcel = 1 transaction)
if (level === 'parcels') {
return [
'interpolate',
['linear'],
['coalesce', ['get', priceField], 0],
...stops
];
}
// For other levels: 0 transactions -> dark gray, <5 -> light gray, else color
return [
'case',
['==', ['coalesce', ['get', countField], 0], 0],
'#999999', // Dark gray for no transactions
['<', ['coalesce', ['get', countField], 0], 5],
'#cccccc', // Light gray for insufficient data
[
'interpolate',
['linear'],
['coalesce', ['get', priceField], 0],
...stops
]
];
}
// Update legend labels based on current level
function updateLegend(level) {
const scale = priceScales[level] || [1500, 3125, 4750, 6375, 8000];
const labels = document.getElementById('legend-labels');
const levelNames = {
country: 'Pays',
regions: 'Régions',
departments: 'Départements',
communes: 'Communes',
iris: 'IRIS (Quartiers)',
parcels: 'Parcelles'
};
// Format number for legend (k for thousands)
const fmt = (n) => n >= 1000 ? `${(n/1000).toFixed(1)}k` : n.toString();
// Update labels (show all 5 values)
labels.innerHTML = `
<span>${fmt(scale[0])}</span>
<span>${fmt(scale[1])}</span>
<span>${fmt(scale[2])}</span>
<span>${fmt(scale[3])}</span>
<span>${fmt(scale[4])}</span>
`;
document.getElementById('current-level').textContent = `Niveau: ${levelNames[level]}`;
}
// Update scales and colors when property type changes
function updateScalesAndColors() {
const priceField = getPriceField();
// Recompute scales for each level based on current property type
['country', 'regions', 'departments', 'iris', 'communes'].forEach(level => {
if (geoData[level]) {
priceScales[level] = computePriceScale(geoData[level].features, priceField, level);
}
});
// Parcels use the same fixed scale
priceScales['parcels'] = [1500, 3125, 4750, 6375, 8000];
// Update layer colors
['country', 'regions', 'departments', 'iris', 'communes'].forEach(level => {
const layerId = `${level}-fill`;
if (map.getLayer(layerId)) {
map.setPaintProperty(layerId, 'fill-color', buildFillColor(level));
}
});
// Update parcels layer color (vector tiles)
if (map.getLayer('parcels-fill')) {
map.setPaintProperty('parcels-fill', 'fill-color', buildFillColor('parcels'));
}
// Update legend
updateLegend(currentLevel);
}
// Update all layer colors when property type changes
function updateLayerColors() {
updateScalesAndColors();
}
// Determine current level based on zoom
function getLevelFromZoom(zoom) {
if (zoom < 5) return 'country';
if (zoom < 7) return 'regions';
if (zoom < 9) return 'departments';
if (zoom < 11) return 'communes';
if (zoom < 13) return 'iris';
return 'parcels';
}
map.on('load', async () => {
// Load all GeoJSON data in parallel for faster startup
const levels = ['country', 'regions', 'departments', 'iris', 'communes'];
const priceField = getPriceField();
const fetchPromises = levels.map(level =>
fetch(`data/${level}.geojson`).then(r => r.json())
);
const results = await Promise.all(fetchPromises);
levels.forEach((level, i) => {
geoData[level] = results[i];
priceScales[level] = computePriceScale(geoData[level].features, priceField, level);
console.log(`${level} scale:`, priceScales[level]);
});
// Store communes data for top cities panel
topCitiesData = geoData.communes.features;
updateTopCitiesPanel();
showTopCities(true); // Show at initial country level
// Add country source and layers
map.addSource('country', {
type: 'geojson',
data: geoData.country
});
map.addLayer({
id: 'country-fill',
type: 'fill',
source: 'country',
paint: {
'fill-color': buildFillColor('country'),
'fill-opacity': 0.7
},
maxzoom: 5
});
map.addLayer({
id: 'country-line',
type: 'line',
source: 'country',
paint: {
'line-color': '#333',
'line-width': 2
},
maxzoom: 5
});
// Add regions source and layers
map.addSource('regions', {
type: 'geojson',
data: geoData.regions
});
map.addLayer({
id: 'regions-fill',
type: 'fill',
source: 'regions',
paint: {
'fill-color': buildFillColor('regions'),
'fill-opacity': 0.7
},
minzoom: 5,
maxzoom: 7
});
map.addLayer({
id: 'regions-line',
type: 'line',
source: 'regions',
paint: {
'line-color': '#333',
'line-width': 1.5
},
minzoom: 5,
maxzoom: 7
});
// Add departments source and layers
map.addSource('departments', {
type: 'geojson',
data: geoData.departments
});
map.addLayer({
id: 'departments-fill',
type: 'fill',
source: 'departments',
paint: {
'fill-color': buildFillColor('departments'),
'fill-opacity': 0.7
},
minzoom: 7,
maxzoom: 9
});
map.addLayer({
id: 'departments-line',
type: 'line',
source: 'departments',
paint: {
'line-color': '#333',
'line-width': 1
},
minzoom: 7,
maxzoom: 9
});
// Add IRIS (neighborhoods) source and layers
map.addSource('iris', {
type: 'geojson',
data: geoData.iris
});
map.addLayer({
id: 'iris-fill',
type: 'fill',
source: 'iris',
paint: {
'fill-color': buildFillColor('iris'),
'fill-opacity': 0.7
},
minzoom: 11,
maxzoom: 13
});
map.addLayer({
id: 'iris-line',
type: 'line',
source: 'iris',
paint: {
'line-color': '#555',
'line-width': 0.5
},
minzoom: 11,
maxzoom: 13
});
// Add parcels source (PMTiles) and layers
// Only add if PMTiles protocol is available
if (pmtilesAvailable) {
try {
map.addSource('parcels', {
type: 'vector',
url: 'pmtiles://data/parcels.pmtiles'
});
map.addLayer({
id: 'parcels-fill',
type: 'fill',
source: 'parcels',
'source-layer': 'parcels',
paint: {
'fill-color': buildFillColor('parcels'),
'fill-opacity': 0.8
},
minzoom: 13
});
map.addLayer({
id: 'parcels-line',
type: 'line',
source: 'parcels',
'source-layer': 'parcels',
paint: {
'line-color': '#333',
'line-width': 0.3
},
minzoom: 13
});
console.log('Parcels PMTiles layer added');
} catch (e) {
console.log('Parcels PMTiles not available:', e.message);
}
} else {
console.log('PMTiles not available, skipping parcels layer');
}
// Add communes source and layers
map.addSource('communes', {
type: 'geojson',
data: geoData.communes
});
map.addLayer({
id: 'communes-fill',
type: 'fill',
source: 'communes',
paint: {
'fill-color': buildFillColor('communes'),
'fill-opacity': 0.7
},
minzoom: 9,
maxzoom: 11
});
map.addLayer({
id: 'communes-line',
type: 'line',
source: 'communes',
paint: {
'line-color': '#666',
'line-width': 0.5
},
minzoom: 9,
maxzoom: 11
});
// Hover interactions for each layer
['country', 'regions', 'departments', 'iris', 'communes'].forEach(layer => {
map.on('mousemove', `${layer}-fill`, (e) => {
map.getCanvas().style.cursor = 'pointer';
if (e.features.length > 0) {
updateInfo(e.features[0].properties, layer);
}
});
map.on('mouseleave', `${layer}-fill`, () => {
map.getCanvas().style.cursor = '';
resetInfo();
});
});
// Separate hover handler for parcels (vector tiles)
if (map.getSource('parcels')) {
map.on('mousemove', 'parcels-fill', (e) => {
map.getCanvas().style.cursor = 'pointer';
if (e.features.length > 0) {
updateInfo(e.features[0].properties, 'parcels');
}
});
map.on('mouseleave', 'parcels-fill', () => {
map.getCanvas().style.cursor = '';
resetInfo();
});
}
// Initial legend update
updateLegend(getLevelFromZoom(map.getZoom()));
});
// Update zoom display and legend
map.on('zoom', () => {
const zoom = map.getZoom();
document.getElementById('zoom-value').textContent = zoom.toFixed(1);
const newLevel = getLevelFromZoom(zoom);
if (newLevel !== currentLevel) {
currentLevel = newLevel;
updateLegend(currentLevel);
}
});
// Property type selector
document.getElementById('property-type').addEventListener('change', (e) => {
currentPropertyType = e.target.value;
updateLayerColors();
updateTopCitiesPanel();
});
// Add navigation controls
map.addControl(new maplibregl.NavigationControl());
</script>
</body>
</html>
|