File size: 20,647 Bytes
d3b7829 |
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 |
import folium
from folium import plugins
import json
import os
import pandas as pd
from collections import Counter
import folium
from folium import plugins
import json
import os
import pandas as pd
from collections import Counter
def load_case_data_from_csv(filter_year='all', filter_crime='all', filter_city='all'):
"""Load case data from a single cleaned CSV file."""
cleaned_csv_path = "/app/cleaned_data.csv"
if not os.path.exists(cleaned_csv_path):
raise FileNotFoundError(f"{cleaned_csv_path} not found.")
# load 1 file saja
data = pd.read_csv(cleaned_csv_path, on_bad_lines='skip')
# normalisasi ke lowercase
data_lower = data.map(
lambda x: x.lower().strip() if isinstance(x, str) and x.strip() != "" else x
)
# normalisasi nama pengadilan → ambil kota-nya saja
if 'lembaga_peradilan' in data_lower.columns:
data_lower['kota'] = (
data_lower['lembaga_peradilan']
.str.replace(r'^pn\s+', '', regex=True)
.str.strip()
.str.title()
)
else:
data_lower['kota'] = None
# parsing tanggal
if 'tanggal_musyawarah' in data_lower.columns:
data_lower['tanggal'] = pd.to_datetime(
data_lower['tanggal_musyawarah'], errors='coerce'
)
data_lower['tahun_putusan'] = data_lower['tanggal'].dt.year.astype('Int64')
df = data_lower.copy()
# filter year
if filter_year != 'all':
try:
year_val = int(filter_year)
df = df[df['tahun_putusan'] == year_val]
except:
pass
# filter crime
if filter_crime != 'all' and 'kata_kunci' in df.columns:
df = df[df['kata_kunci'] == filter_crime.lower()]
# filter city
if filter_city != 'all':
df = df[df['kota'].str.lower() == filter_city.lower()]
if df.empty:
return {}
# agregasi
case_data = {}
# group by kota
grouped = df.groupby('kota')
for kota, group in grouped:
total_cases = len(group)
# ambil top 10 kejahatan
if 'kata_kunci' in group.columns:
crime_counts = group['kata_kunci'].value_counts().head(10)
else:
crime_counts = {}
cases = {crime.title(): int(count) for crime, count in crime_counts.items()}
case_data[kota] = {
'total': total_cases,
'cases': cases,
}
return case_data
def create_heatmap_interactive(filter_year='all', filter_crime='all', filter_city='all'):
"""Create an interactive Folium choropleth heatmap with click-to-zoom and case information.
Args:
filter_year: Filter by specific year or 'all' for all years
filter_crime: Filter by specific crime type or 'all' for all crimes
filter_city: Filter by specific city/kabupaten or 'all' for all cities
Returns:
str: HTML string for embedding the Folium map.
"""
# Load real case data from CSV with filters
real_case_data = load_case_data_from_csv(filter_year=filter_year, filter_crime=filter_crime, filter_city=filter_city)
# Load GeoJSON data with metric
try:
with open('app/static/geojson/jatim_kabkota_metric.geojson', encoding='utf-8') as f:
geojson_data = json.load(f)
except:
# Fallback to original if metric version doesn't exist
with open('data/geojson/jatim_kabkota.geojson', encoding='utf-8') as f:
geojson_data = json.load(f)
# Update features with real case data
for feature in geojson_data['features']:
kabupaten_name = feature['properties'].get('name', feature['properties'].get('NAMOBJ', ''))
if kabupaten_name in real_case_data:
# Use real data
data = real_case_data[kabupaten_name]
feature['properties']['metric'] = data['total']
feature['properties']['cases'] = data['cases']
feature['properties']['total_cases'] = data['total']
else:
# Fallback jika tidak ada data
feature['properties']['metric'] = 0
feature['properties']['cases'] = {}
feature['properties']['total_cases'] = 0
# Calculate bounds from all features for Jawa Timur only
all_bounds = []
for feature in geojson_data['features']:
geom = feature['geometry']
if geom['type'] == 'Polygon':
for coord in geom['coordinates'][0]:
all_bounds.append([coord[1], coord[0]])
elif geom['type'] == 'MultiPolygon':
for poly in geom['coordinates']:
for coord in poly[0]:
all_bounds.append([coord[1], coord[0]])
# Get min/max bounds for Jawa Timur
if all_bounds:
lats = [b[0] for b in all_bounds]
lons = [b[1] for b in all_bounds]
min_lat, max_lat = min(lats), max(lats)
min_lon, max_lon = min(lons), max(lons)
# Add small buffer (0.1 degrees)
buffer = 0.1
bounds = [
[min_lat - buffer, min_lon - buffer], # Southwest
[max_lat + buffer, max_lon + buffer] # Northeast
]
else:
# Fallback bounds for Jawa Timur
bounds = [[-8.8, 111.0], [-6.0, 114.5]]
# Create Folium map with restricted bounds
m = folium.Map(
location=[-7.5, 112.5],
zoom_start=9, # Start zoom level 9 - nyaman lihat seluruh Jatim
min_zoom=8, # Min zoom 8 - bisa lihat peta lebih luas sedikit
max_zoom=13, # Max zoom 13 - cukup untuk detail
tiles=None, # No tiles initially
zoom_control=True, # Tampilkan tombol zoom
scrollWheelZoom=False, # Matikan scroll wheel zoom - hanya pakai tombol
prefer_canvas=True,
max_bounds=True,
min_lat=bounds[0][0],
max_lat=bounds[1][0],
min_lon=bounds[0][1],
max_lon=bounds[1][1]
)
# Add tiles only for Jawa Timur area using TileLayer with bounds
folium.TileLayer(
tiles='CartoDB positron',
attr='CartoDB',
name='Base Map',
overlay=False,
control=False,
bounds=bounds
).add_to(m)
# Don't use fit_bounds here - it will override zoom_start
# Instead, we set zoom_start=9 above and let JavaScript handle bounds
# Create choropleth layer
choropleth = folium.Choropleth(
geo_data=geojson_data,
name='Legal Case Heatmap',
data={f['properties']['name']: f['properties']['metric'] for f in geojson_data['features']},
columns=['name', 'metric'],
key_on='feature.properties.name',
fill_color='OrRd',
fill_opacity=0.8,
line_opacity=0.5,
line_weight=1.5,
legend_name='Number of Cases',
highlight=True,
).add_to(m)
# Add interactive tooltips and popups with click-to-zoom
for feature in geojson_data['features']:
props = feature['properties']
name = props.get('name', 'Unknown')
total = props.get('total_cases', props.get('metric', 0))
cases = props.get('cases', {})
# Get centroid for marker
lat = props.get('centroid_lat')
lon = props.get('centroid_lon')
# Create detailed popup content
case_list = '<br>'.join([f'<strong>{k}:</strong> {v} case' for k, v in cases.items() if v > 0])
popup_html = f'''
<div style="font-family: Arial, sans-serif; width: 280px;">
<h3 style="margin: 0 0 10px 0;
color: #2C5F8D;
border-bottom: 2px solid #2C5F8D;
padding-bottom: 5px;">
{name}
</h3>
<div style="margin-bottom: 10px;">
<strong style="font-size: 16px; color: #d32f2f;">
Number of Cases: {total}
</strong>
</div>
<div style="margin-top: 10px;">
<strong>Detailed Information:</strong><br>
<div style="margin-top: 8px;
font-size: 13px;
line-height: 1.6;
background: #f5f5f5;
padding: 10px;
border-radius: 5px;">
{case_list if case_list else '<em>No data</em>'}
</div>
</div>
<div style="margin-top: 12px;
padding-top: 10px;
border-top: 1px solid #ddd;
font-size: 11px;
color: #666;">
<em>Click for zoom in</em>
</div>
</div>
'''
# Compact tooltip for hover - stays close to cursor
tooltip_html = f'''
<div style="font-family: Arial, sans-serif;
padding: 8px 12px;
background: rgba(44, 95, 141, 0.95);
color: white;
border-radius: 5px;
box-shadow: 0 2px 8px rgba(0,0,0,0.3);
font-size: 13px;
white-space: nowrap;
border: 2px solid white;">
<strong style="font-size: 14px;">{name}</strong><br>
<span style="font-size: 12px;">📊 Total: {total} case</span>
</div>
'''
# Add GeoJson layer with popup for each feature
geo_json = folium.GeoJson(
feature,
name=name,
style_function=lambda x: {
'fillColor': 'transparent',
'color': 'transparent',
'weight': 0,
'fillOpacity': 0
},
highlight_function=lambda x: {
'fillColor': '#ffeb3b',
'color': '#ff5722',
'weight': 3,
'fillOpacity': 0.7
},
tooltip=folium.Tooltip(
tooltip_html,
sticky=True, # Tooltip follows cursor closely
style="""
background-color: transparent;
border: none;
box-shadow: none;
padding: 0;
margin: 0;
"""
),
popup=folium.Popup(popup_html, max_width=300)
)
geo_json.add_to(m)
# Add click event to zoom to feature bounds
if lat and lon:
# Calculate bounds from geometry
geom = feature['geometry']
bounds = []
if geom['type'] == 'Polygon':
for coord in geom['coordinates'][0]:
bounds.append([coord[1], coord[0]])
elif geom['type'] == 'MultiPolygon':
for poly in geom['coordinates']:
for coord in poly[0]:
bounds.append([coord[1], coord[0]])
if bounds:
# Add invisible marker for click-to-zoom functionality
marker = folium.Marker(
location=[lat, lon],
icon=folium.DivIcon(html=''),
tooltip=None,
popup=None
)
# Add JavaScript for zoom on click
bounds_str = str(bounds).replace("'", '"')
marker_html = f'''
<script>
var bounds_{name.replace(" ", "_").replace(".", "")} = {bounds_str};
</script>
'''
m.get_root().html.add_child(folium.Element(marker_html))
# # Add legend
# legend_html = '''
# <div style="position: fixed;
# bottom: 50px; left: 50px; width: 300px;
# background-color: white; z-index:9999;
# border:2px solid #2C5F8D; border-radius: 8px;
# padding: 15px;
# box-shadow: 0 4px 8px rgba(0,0,0,0.3);
# font-family: Arial, sans-serif;">
# </div>
# '''
# m.get_root().html.add_child(folium.Element(legend_html))
# Add custom CSS for better interactivity and sticky tooltip
custom_css = '''
<style>
.leaflet-container {
background-color: #e0e0e0 !important;
cursor: pointer !important;
}
/* Tooltip styling - stays very close to cursor */
.leaflet-tooltip {
background-color: transparent !important;
border: none !important;
box-shadow: none !important;
padding: 0 !important;
margin: 0 !important;
pointer-events: none !important;
}
.leaflet-tooltip-top {
margin-top: -5px !important;
}
.leaflet-tooltip-left {
margin-left: -5px !important;
}
.leaflet-tooltip-right {
margin-left: 5px !important;
}
.leaflet-tooltip-bottom {
margin-top: 5px !important;
}
/* Hide default tooltip pointer */
.leaflet-tooltip-top:before,
.leaflet-tooltip-bottom:before,
.leaflet-tooltip-left:before,
.leaflet-tooltip-right:before {
display: none !important;
}
/* Hide tiles outside bounds */
.leaflet-tile-container {
clip-path: inset(0);
}
.leaflet-interactive:hover {
stroke: #ff5722 !important;
stroke-width: 2px !important;
stroke-opacity: 1 !important;
}
.leaflet-popup-content-wrapper {
border-radius: 8px !important;
box-shadow: 0 4px 12px rgba(0,0,0,0.3) !important;
}
.leaflet-popup-tip {
display: none !important;
}
/* Add border around Jawa Timur */
.leaflet-overlay-pane svg {
filter: drop-shadow(0 0 3px rgba(0,0,0,0.3));
}
</style>
'''
m.get_root().html.add_child(folium.Element(custom_css))
map_name = m.get_name()
# Add JavaScript to restrict panning to Jawa Timur bounds
restrict_bounds_script = f'''
<script>
// Restrict map to Jawa Timur bounds only
document.addEventListener('DOMContentLoaded', function() {{
setTimeout(function() {{
// Get the Leaflet map instance
var mapElement = window.{map_name};
if (mapElement && mapElement._leaflet_id) {{
var map = mapElement;
// Set max bounds for Jawa Timur
var bounds = L.latLngBounds(
L.latLng({bounds[0][0]}, {bounds[0][1]}), // Southwest
L.latLng({bounds[1][0]}, {bounds[1][1]}) // Northeast
);
// Strict bounds - cannot pan outside
//map.setMaxBounds(bounds);
//map.options.maxBoundsViscosity = 0.6; // Make bounds completely rigid
// Set zoom constraints directly on map options
map.options.minZoom = 8;
map.options.maxZoom = 13;
// Remove existing zoom control and add new one with correct limits
if (map.zoomControl) {{
map.removeControl(map.zoomControl);
}}
L.control.zoom({{ position: 'topleft' }}).addTo(map);
// Enforce zoom limits on all zoom events
map.on('zoom', function() {{
var currentZoom = map.getZoom();
if (currentZoom < 8) {{
map.setZoom(8, {{ animate: false }});
return false;
}} else if (currentZoom > 13) {{
map.setZoom(13, {{ animate: false }});
return false;
}}
}});
// Also on zoomend to catch any missed events
map.on('zoomend', function() {{
var currentZoom = map.getZoom();
if (currentZoom < 8) {{
map.setZoom(8, {{ animate: false }});
}} else if (currentZoom > 13) {{
map.setZoom(13, {{ animate: false }});
}}
updateZoomControl();
}});
// Update zoom control state
function updateZoomControl() {{
var zoom = map.getZoom();
var zoomInButton = document.querySelector('.leaflet-control-zoom-in');
var zoomOutButton = document.querySelector('.leaflet-control-zoom-out');
if (zoomInButton) {{
if (zoom >= 13) {{
zoomInButton.classList.add('leaflet-disabled');
zoomInButton.style.cursor = 'not-allowed';
zoomInButton.style.opacity = '0.4';
zoomInButton.style.pointerEvents = 'none';
zoomInButton.setAttribute('disabled', 'disabled');
}} else {{
zoomInButton.classList.remove('leaflet-disabled');
zoomInButton.style.cursor = 'pointer';
zoomInButton.style.opacity = '1';
zoomInButton.style.pointerEvents = 'auto';
zoomInButton.removeAttribute('disabled');
}}
}}
if (zoomOutButton) {{
if (zoom <= 8) {{
zoomOutButton.classList.add('leaflet-disabled');
zoomOutButton.style.cursor = 'not-allowed';
zoomOutButton.style.opacity = '0.4';
zoomOutButton.style.pointerEvents = 'none';
zoomOutButton.setAttribute('disabled', 'disabled');
}} else {{
zoomOutButton.classList.remove('leaflet-disabled');
zoomOutButton.style.cursor = 'pointer';
zoomOutButton.style.opacity = '1';
zoomOutButton.style.pointerEvents = 'auto';
zoomOutButton.removeAttribute('disabled');
}}
}}
}}
// Call on every zoom change
map.on('zoom', updateZoomControl);
map.on('zoomend', updateZoomControl);
updateZoomControl(); // Call immediately
// Hide tiles outside bounds by clipping
var tileLayer = document.querySelector('.leaflet-tile-pane');
if (tileLayer) {{
// Calculate pixel bounds
var southWest = map.latLngToLayerPoint(bounds.getSouthWest());
var northEast = map.latLngToLayerPoint(bounds.getNorthEast());
// Create clip path
var clipPath = 'rect(' +
northEast.y + 'px, ' +
northEast.x + 'px, ' +
southWest.y + 'px, ' +
southWest.x + 'px)';
// Note: Modern browsers use clip-path instead of clip
}}
}}
// Add click cursor to paths
var paths = document.querySelectorAll('.leaflet-interactive');
paths.forEach(function(path) {{
path.style.cursor = 'pointer';
}});
}}, 1000);
}});
</script>
'''
m.get_root().html.add_child(folium.Element(restrict_bounds_script))
return m._repr_html_()
|