81 İl 973 İlçe Harita Portalı

Türkiye’deki illeri ve ilçeleri etkileşimli harita üzerinde hızlıca görüntülemek için hazırlanmış web tabanlı bir uygulamadır; kullanıcı il seçerek o ile bağlı ilçeleri listeler, ardından istediği ilçeye tıklayarak haritanın doğrudan ilgili ilçe merkezine yakınlaşmasını ve konumu işaretlemesini sağlar. 

Uygulama bilgisayar, tablet ve mobil cihazlarla uyumludur; mobilde ilçe listesi açılır panel olarak çalışır. Kullanmak için HTML dosyasını tarayıcıda açmak, üst bölümden bir il seçmek ve sol taraftaki ilçe listesinden istenen ilçeye tıklamak yeterlidir; başlıktaki seçili il alanına tıklayarak da başlangıç görünümüne dönülebilir.

Bir not defteri açıp aşağıdaki kodu içine koyduktan sonra farklı kaydedin, bir isim verin. dosya uzantısı. ".html" olması yeterlidir.


İl seçimi açılır menüden ve arama penceresinden yapılabilmektedir.


İl seçimi sonrası İlçeler sol tarafta listelenmektedir.


İlçeye tıklama ile, harita görüntüsü ilgili lokasyona zoom yapmaktadır. Seçim sonrası beliren harita konumuna yaklaşıp uzaklaşabilir, farklı konumlara kaydırma yapabilirsiniz.



HTML Kod:
<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
    <meta name="color-scheme" content="light">
    <title>81 İl 973 İlçe Harita Portalı</title>

    <!-- MapLibre GL JS: ana CDN + CSS fallback -->
    <link
        rel="stylesheet"
        href="https://cdn.jsdelivr.net/npm/maplibre-gl@5.24.0/dist/maplibre-gl.css"
        onerror="this.onerror=null;this.href='https://unpkg.com/maplibre-gl@5.24.0/dist/maplibre-gl.css';"
    >
    <script src="https://cdn.jsdelivr.net/npm/maplibre-gl@5.24.0/dist/maplibre-gl.js"></script>

    <style>
        :root {
            --primary: #2c3e50;
            --secondary: #34495e;
            --accent: #27ae60;
            --light: #ecf0f1;
            --panel: #ffffff;
            --danger: #c0392b;
            --warning: #f39c12;
            --shadow: 0 3px 10px rgba(0,0,0,.12);
            --radius: 8px;
            --touch: 44px;
        }

        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
            -webkit-tap-highlight-color: transparent;
        }

        html, body {
            width: 100%;
            height: 100%;
            min-height: 100%;
        }

        html {
            overflow: hidden;
        }

        body {
            font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
            background: var(--light);
            display: flex;
            flex-direction: column;
            height: 100vh;
            height: 100dvh;
            padding:
                max(12px, env(safe-area-inset-top))
                max(12px, env(safe-area-inset-right))
                max(12px, env(safe-area-inset-bottom))
                max(12px, env(safe-area-inset-left));
            overflow: hidden;
            overscroll-behavior: none;
        }

        button, input {
            font: inherit;
        }

        .header {
            display: grid;
            grid-template-columns: auto minmax(280px, 1fr) auto;
            align-items: center;
            gap: 15px;
            padding: 10px 15px;
            margin-bottom: 12px;
            background: var(--panel);
            border: 2px solid #000;
            border-radius: var(--radius);
            box-shadow: var(--shadow);
            flex: 0 0 auto;
        }

        .header-left {
            display: flex;
            align-items: center;
            gap: 12px;
            min-width: 0;
        }

        .logo img {
            display: block;
            height: 46px;
            max-width: 100px;
            object-fit: contain;
        }

        .title1 {
            color: #000;
            font-size: 20px;
            font-weight: 700;
            line-height: 1.1;
            white-space: nowrap;
        }

        .title2 {
            margin-top: 3px;
            color: #555;
            font-size: 11px;
            font-weight: 600;
        }

        .header-center {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            min-width: 0;
        }

        .search-label {
            flex: 0 0 auto;
            color: var(--primary);
            font-size: 15px;
            font-weight: 700;
        }

        .province-search-wrap {
            position: relative;
            width: min(360px, 100%);
        }

        #province-search {
            width: 100%;
            min-height: 40px;
            padding: 8px 38px 8px 12px;
            color: #222;
            background: #fff;
            border: 1px solid #aeb6bf;
            border-radius: 6px;
            outline: none;
        }

        #province-search:focus {
            border-color: var(--accent);
            box-shadow: 0 0 0 2px rgba(39,174,96,.14);
        }

        .search-arrow {
            position: absolute;
            top: 50%;
            right: 12px;
            transform: translateY(-50%);
            color: #687078;
            pointer-events: none;
            font-size: 12px;
        }

        #selected-province-title {
            display: flex;
            align-items: center;
            justify-content: center;
            max-width: 100%;
            min-height: 40px;
            padding: 7px 12px;
            color: var(--primary);
            background: var(--light);
            border: 1px solid #bdc3c7;
            border-radius: 20px;
            font-size: 18px;
            font-weight: 700;
            cursor: pointer;
            user-select: none;
            transition: color .2s, border-color .2s, background .2s;
        }

        #selected-province-title:hover {
            color: var(--accent);
            border-color: var(--accent);
        }

        #selected-province-title .hint {
            margin-left: 8px;
            color: #7f8c8d;
            font-size: 12px;
            font-weight: 400;
        }

        .header-right {
            color: #333;
            font-size: 13px;
            font-weight: 700;
            text-align: right;
            white-space: nowrap;
        }

        .main-container {
            position: relative;
            display: flex;
            flex: 1 1 auto;
            min-width: 0;
            min-height: 0;
            overflow: hidden;
            background: #fff;
            border: 5px solid var(--primary);
            border-radius: var(--radius);
            isolation: isolate;
        }

        .sidebar {
            width: 300px;
            min-width: 300px;
            overflow-y: auto;
            color: #fff;
            background: var(--secondary);
            z-index: 30;
            scrollbar-width: thin;
            overscroll-behavior: contain;
        }

        .sidebar-section {
            padding: 15px;
        }

        .sidebar h3 {
            position: sticky;
            top: 0;
            z-index: 2;
            margin: -15px -15px 12px;
            padding: 14px 15px 10px;
            background: var(--secondary);
            border-bottom: 2px solid var(--accent);
            font-size: 18px;
        }

        .list-item {
            display: flex;
            align-items: center;
            min-height: var(--touch);
            margin-bottom: 6px;
            padding: 10px 12px;
            color: #fff;
            background: rgba(255,255,255,.06);
            border: 0;
            border-radius: 6px;
            font-size: 15px;
            cursor: pointer;
            touch-action: manipulation;
            transition: background .18s, transform .18s;
        }

        .list-item:hover,
        .list-item.active {
            background: var(--accent);
        }

        .list-item:active {
            transform: scale(.99);
        }

        .message-item {
            cursor: default;
            line-height: 1.4;
        }

        .loading-text {
            color: #f1c40f;
            font-style: italic;
        }

        .error-text {
            color: #fff;
            background: rgba(192,57,43,.42);
        }

        #map {
            flex: 1 1 auto;
            width: 100%;
            height: 100%;
            min-width: 0;
            min-height: 240px;
            background: #dfe6e9;
            z-index: 1;
        }

        .hidden {
            display: none !important;
        }

        .district-toggle {
            display: none;
            position: absolute;
            top: 12px;
            left: 12px;
            z-index: 45;
            min-height: var(--touch);
            padding: 0 14px;
            color: #fff;
            background: var(--primary);
            border: 0;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,.24);
            font-weight: 700;
            cursor: pointer;
            touch-action: manipulation;
        }

        .sidebar-backdrop {
            display: none;
        }

        .map-status {
            position: absolute;
            top: 14px;
            left: 50%;
            z-index: 50;
            transform: translateX(-50%);
            max-width: min(760px, calc(100% - 40px));
            padding: 9px 14px;
            color: #fff;
            background: rgba(44,62,80,.94);
            border-radius: 6px;
            box-shadow: 0 2px 8px rgba(0,0,0,.22);
            font-size: 13px;
            line-height: 1.35;
            text-align: center;
            pointer-events: none;
        }

        .map-status.error {
            background: rgba(192,57,43,.96);
        }

        .map-status.warning {
            background: rgba(243,156,18,.96);
        }

        .data-badge {
            position: absolute;
            right: 8px;
            bottom: 8px;
            z-index: 15;
            max-width: calc(100% - 16px);
            padding: 5px 8px;
            color: rgba(255,255,255,.92);
            background: rgba(44,62,80,.82);
            border-radius: 5px;
            font-size: 10px;
            line-height: 1.2;
            pointer-events: none;
        }

        .maplibregl-ctrl-top-right {
            top: 4px;
            right: 4px;
        }

        .maplibregl-ctrl-group button {
            width: 36px;
            height: 36px;
        }

        .maplibregl-ctrl-attrib {
            font-size: 10px;
        }

        @media (max-width: 1024px) {
            .header {
                grid-template-columns: minmax(0, 1fr) auto;
            }

            .header-center {
                grid-column: 1 / -1;
                grid-row: 2;
                justify-content: stretch;
            }

            .province-search-wrap {
                width: 100%;
            }

            .sidebar {
                width: 270px;
                min-width: 270px;
            }
        }

        @media (max-width: 700px) {
            body {
                padding:
                    max(6px, env(safe-area-inset-top))
                    max(6px, env(safe-area-inset-right))
                    max(6px, env(safe-area-inset-bottom))
                    max(6px, env(safe-area-inset-left));
            }

            .header {
                grid-template-columns: minmax(0, 1fr);
                gap: 8px;
                padding: 8px 10px;
                margin-bottom: 6px;
                border-width: 1px;
            }

            .header-left {
                justify-content: center;
            }

            .logo img {
                height: 36px;
                max-width: 70px;
            }

            .title1 {
                font-size: clamp(15px, 4.5vw, 18px);
                line-height: 1.12;
                text-align: center;
                white-space: normal;
            }

            .title2 {
                font-size: 10px;
                text-align: center;
            }

            .header-right {
                display: none;
            }

            .header-center {
                grid-column: 1;
                grid-row: auto;
                flex-direction: column;
                width: 100%;
                gap: 6px;
            }

            .search-label {
                align-self: flex-start;
                font-size: 13px;
            }

            .province-search-wrap {
                width: 100%;
            }

            #province-search,
            #selected-province-title {
                min-height: var(--touch);
            }

            #selected-province-title {
                width: 100%;
                padding: 8px 10px;
                border-radius: 8px;
                font-size: 15px;
            }

            #selected-province-title .hint {
                display: none;
            }

            .main-container {
                border-width: 2px;
                border-radius: 6px;
            }

            .sidebar {
                position: absolute;
                inset: 0 auto 0 0;
                display: block;
                width: min(86vw, 330px);
                min-width: 0;
                max-width: 330px;
                transform: translateX(-105%);
                transition: transform .22s ease;
                box-shadow: 8px 0 24px rgba(0,0,0,.22);
            }

            .sidebar.mobile-open {
                transform: translateX(0);
            }

            .sidebar-backdrop {
                position: absolute;
                inset: 0;
                z-index: 25;
                background: rgba(0,0,0,.32);
            }

            .sidebar-backdrop.active {
                display: block;
            }

            .district-toggle {
                display: block;
            }

            .district-toggle.hidden {
                display: none !important;
            }

            .map-status {
                top: 62px;
                width: calc(100% - 24px);
                max-width: none;
                padding: 8px 10px;
                font-size: 12px;
            }

            .data-badge {
                max-width: 72vw;
            }

            .maplibregl-ctrl-top-right {
                top: 7px;
                right: 7px;
            }

            .maplibregl-ctrl-group button {
                width: 40px;
                height: 40px;
            }

            .maplibregl-ctrl-attrib {
                max-width: 72vw;
            }
        }

        @media (max-width: 380px) {
            .header-left {
                gap: 7px;
            }

            .logo img {
                height: 30px;
                max-width: 55px;
            }

            .title1 {
                font-size: 14px;
            }

            .sidebar {
                width: 90vw;
            }
        }

        @media (max-width: 900px) and (orientation: landscape) and (max-height: 520px) {
            body {
                padding: 4px;
            }

            .header {
                grid-template-columns: auto minmax(220px, 1fr);
                padding: 5px 8px;
                margin-bottom: 4px;
            }

            .header-left {
                justify-content: flex-start;
            }

            .logo img {
                height: 28px;
            }

            .title1 {
                font-size: 14px;
                white-space: nowrap;
            }

            .title2,
            .header-right,
            .search-label {
                display: none;
            }

            .header-center {
                grid-column: 2;
                grid-row: 1;
                flex-direction: row;
            }

            #province-search,
            #selected-province-title {
                min-height: 36px;
            }
        }

        @media (hover: none) {
            .list-item:hover {
                background: rgba(255,255,255,.06);
            }

            .list-item.active {
                background: var(--accent);
            }
        }
    </style>
</head>
<body>
    <header class="header">
        <div class="header-left">
            <div class="logo">
                <img src="logo.jpg" alt="Logo" onerror="this.style.display='none'">
            </div>
            <div>
                <div class="title1">81 İl 973 İlçe Harita Portalı</div>
                <div class="title2">Muhammed Yusuf OLGUN</div>
            </div>
        </div>

        <div class="header-center">
            <span id="search-label" class="search-label">İl Seçiniz:</span>

            <div id="province-search-wrap" class="province-search-wrap">
                <input
                    id="province-search"
                    type="text"
                    list="province-options"
                    autocomplete="off"
                    spellcheck="false"
                    placeholder="İl arayın veya seçin..."
                    aria-label="İl arayın veya seçin"
                >
                <span class="search-arrow">▼</span>
                <datalist id="province-options"></datalist>
            </div>

            <div id="selected-province-title" class="hidden" title="Başa dönmek için tıklayın">
                <span id="p-name"></span>
                <span class="hint">(Başa dönmek ve sıfırlamak için tıklayın)</span>
            </div>
        </div>

        <div class="header-right">AI Web Designer:<br>Deneyim</div>
    </header>

    <main class="main-container">
        <button
            id="district-toggle"
            class="district-toggle hidden"
            type="button"
            aria-controls="sidebar"
            aria-expanded="false"
        >☰ İlçeler</button>

        <div id="sidebar-backdrop" class="sidebar-backdrop"></div>

        <aside id="sidebar" class="sidebar hidden" aria-label="İlçe listesi">
            <div class="sidebar-section">
                <h3>İlçeler (<span id="district-count">0</span>)</h3>
                <div id="district-list"></div>
            </div>
        </aside>

        <div id="map" aria-label="Türkiye haritası"></div>
        <div id="map-status" class="map-status">Harita ve konum verileri yükleniyor...</div>
        <div id="data-badge" class="data-badge hidden"></div>
    </main>

    <script>
        "use strict";

        const CONFIG = {
            mapStyle: "https://tiles.openfreemap.org/styles/liberty",
            // Aynı veri setinin iki aynası kullanılıyor. Her ilçe kendi ilinin altında
            // ve ilçe merkezini temsil eden latitude/longitude ile geliyor.
            districtCenterSources: [
                "https://cdn.jsdelivr.net/gh/BuNickTamYirmiHarfli/turkey-cities-districts-json@main/cities.json",
                "https://raw.githubusercontent.com/BuNickTamYirmiHarfli/turkey-cities-districts-json/main/cities.json"
            ],
            turkeyCenter: [35.0, 39.0],
            turkeyZoom: 5.2
        };

        let map = null;
        let mapReady = false;
        let activeMarker = null;
        let pendingView = null;

        let provinces = [];
        let districts = [];
        let provincesByKey = new Map();
        let districtsByProvinceId = new Map();
        let selectedProvince = null;

        const $ = (id) => document.getElementById(id);

        function cleanName(value) {
            return String(value ?? "")
                .replace(/i\u0307/g, "i")
                .replace(/I\u0307/g, "İ")
                .normalize("NFC")
                .trim();
        }

        function searchKey(value) {
            return cleanName(value)
                .toLocaleLowerCase("tr-TR")
                .normalize("NFD")
                .replace(/[\u0300-\u036f]/g, "")
                .replace(/ı/g, "i")
                .replace(/ç/g, "c")
                .replace(/ğ/g, "g")
                .replace(/ö/g, "o")
                .replace(/ş/g, "s")
                .replace(/ü/g, "u")
                .replace(/\s+/g, " ")
                .trim();
        }

        function setStatus(message, type = "normal", autoHide = false) {
            const el = $("map-status");
            if (!el) return;

            clearTimeout(setStatus.timer);
            el.textContent = message;
            el.classList.remove("hidden", "error", "warning");

            if (type === "error") el.classList.add("error");
            if (type === "warning") el.classList.add("warning");

            if (autoHide) {
                setStatus.timer = setTimeout(() => el.classList.add("hidden"), 2400);
            }
        }

        function hideStatus() {
            $("map-status")?.classList.add("hidden");
        }

        async function ensureMapLibre() {
            if (window.maplibregl) return true;

            return new Promise((resolve) => {
                const script = document.createElement("script");
                script.src = "https://unpkg.com/maplibre-gl@5.24.0/dist/maplibre-gl.js";
                script.onload = () => resolve(!!window.maplibregl);
                script.onerror = () => resolve(false);
                document.head.appendChild(script);
            });
        }

        async function fetchJson(url, timeoutMs = 15000) {
            const controller = new AbortController();
            const timeout = setTimeout(() => controller.abort(), timeoutMs);

            try {
                const response = await fetch(url, {
                    method: "GET",
                    mode: "cors",
                    cache: "default",
                    headers: { "Accept": "application/json" },
                    signal: controller.signal
                });

                if (!response.ok) {
                    throw new Error(`HTTP ${response.status} ${response.statusText}`);
                }

                return await response.json();
            } finally {
                clearTimeout(timeout);
            }
        }

        function normalizeDistrictCenterData(payload) {
            if (!Array.isArray(payload)) {
                throw new Error("İl/ilçe veri biçimi geçersiz.");
            }

            const normalizedProvinces = [];
            const normalizedDistricts = [];

            for (const city of payload) {
                const provinceId = String(city.id ?? city.slug ?? city.name ?? "");
                const provinceName = cleanName(city.name);
                const provinceLat = Number(city.latitude);
                const provinceLon = Number(city.longitude);

                if (!provinceId || !provinceName || !Number.isFinite(provinceLat) || !Number.isFinite(provinceLon)) {
                    continue;
                }

                normalizedProvinces.push({
                    id: provinceId,
                    name: provinceName,
                    lat: provinceLat,
                    lon: provinceLon,
                    slug: String(city.slug ?? "")
                });

                const towns = Array.isArray(city.towns) ? city.towns : [];
                for (let i = 0; i < towns.length; i++) {
                    const town = towns[i];
                    const townName = cleanName(town.name);
                    const lat = Number(town.latitude);
                    const lon = Number(town.longitude);

                    if (!townName || !Number.isFinite(lat) || !Number.isFinite(lon)) {
                        continue;
                    }

                    normalizedDistricts.push({
                        id: `${provinceId}-${town.slug || searchKey(townName)}-${i}`,
                        provinceId,
                        name: townName,
                        lat,
                        lon,
                        slug: String(town.slug ?? "")
                    });
                }
            }

            return {
                provinces: normalizedProvinces,
                districts: normalizedDistricts
            };
        }

        async function loadAdministrativeData() {
            let lastError = null;

            for (const url of CONFIG.districtCenterSources) {
                try {
                    const payload = await fetchJson(url);
                    const normalized = normalizeDistrictCenterData(payload);

                    if (normalized.provinces.length !== 81) {
                        throw new Error(`İl sayısı beklenenden farklı: ${normalized.provinces.length}`);
                    }

                    if (normalized.districts.length < 970) {
                        throw new Error(`İlçe sayısı eksik: ${normalized.districts.length}`);
                    }

                    return {
                        provinces: normalized.provinces,
                        districts: normalized.districts,
                        source: "İlçe merkez koordinat veri seti"
                    };
                } catch (error) {
                    lastError = error;
                    console.warn("Koordinat veri aynası kullanılamadı:", url, error);
                }
            }

            throw lastError || new Error("İlçe merkez koordinat verisi yüklenemedi.");
        }

        function buildIndexes() {
            provinces.sort((a, b) => a.name.localeCompare(b.name, "tr"));
            districts.sort((a, b) => a.name.localeCompare(b.name, "tr"));

            provincesByKey = new Map();
            districtsByProvinceId = new Map();

            for (const province of provinces) {
                provincesByKey.set(searchKey(province.name), province);
            }

            for (const district of districts) {
                if (!districtsByProvinceId.has(district.provinceId)) {
                    districtsByProvinceId.set(district.provinceId, []);
                }
                districtsByProvinceId.get(district.provinceId).push(district);
            }
        }

        function populateProvinceOptions() {
            const datalist = $("province-options");
            datalist.innerHTML = "";

            for (const province of provinces) {
                const option = document.createElement("option");
                option.value = province.name;
                datalist.appendChild(option);
            }

            $("province-search").placeholder = "İl arayın veya seçin...";
        }

        function initMap() {
            if (!window.maplibregl) {
                setStatus(
                    "Harita kütüphanesi yüklenemedi. Ağ veya kurum güvenlik duvarı CDN erişimini engelliyor olabilir.",
                    "error"
                );
                return;
            }

            try {
                map = new maplibregl.Map({
                    container: "map",
                    style: CONFIG.mapStyle,
                    center: CONFIG.turkeyCenter,
                    zoom: CONFIG.turkeyZoom,
                    minZoom: 4,
                    maxZoom: 18,
                    attributionControl: true
                });

                map.addControl(new maplibregl.NavigationControl(), "top-right");

                map.on("load", () => {
                    mapReady = true;
                    resizeMapSoon();

                    if (pendingView) {
                        const view = pendingView;
                        pendingView = null;
                        goTo(view.lon, view.lat, view.zoom, view.label);
                    } else if (provinces.length) {
                        hideStatus();
                    }
                });

                map.on("error", (event) => {
                    const message = String(event?.error?.message || event?.error || "");
                    console.error("Harita hatası:", event?.error || event);

                    if (/403|forbidden|failed to fetch|network|style/i.test(message)) {
                        setStatus(
                            "Harita arka planı yüklenemedi. OpenFreeMap erişimi ağ veya güvenlik duvarı tarafından engellenmiş olabilir.",
                            "error"
                        );
                    }
                });
            } catch (error) {
                console.error(error);
                setStatus(`Harita başlatılamadı: ${error.message}`, "error");
            }
        }

        function resizeMapSoon() {
            if (!map) return;
            setTimeout(() => map.resize(), 60);
            setTimeout(() => map.resize(), 220);
        }

        function setMarker(lon, lat, label) {
            if (!map || !mapReady) return;

            if (activeMarker) {
                activeMarker.remove();
                activeMarker = null;
            }

            activeMarker = new maplibregl.Marker({ color: "#e74c3c" })
                .setLngLat([lon, lat])
                .setPopup(
                    new maplibregl.Popup({ offset: 22 })
                        .setText(label)
                )
                .addTo(map);
        }

        function goTo(lon, lat, zoom, label = "") {
            lon = Number(lon);
            lat = Number(lat);

            if (!Number.isFinite(lon) || !Number.isFinite(lat)) {
                setStatus("Seçilen konumun koordinatı geçersiz.", "error", true);
                return;
            }

            if (!map || !mapReady) {
                pendingView = { lon, lat, zoom, label };
                return;
            }

            map.flyTo({
                center: [lon, lat],
                zoom,
                speed: 1.25,
                curve: 1.35,
                essential: true
            });

            setMarker(lon, lat, label);
        }

        function renderDistricts(province) {
            const list = $("district-list");
            const rows = districtsByProvinceId.get(province.id) || [];

            list.innerHTML = "";
            $("district-count").textContent = String(rows.length);

            if (!rows.length) {
                const msg = document.createElement("div");
                msg.className = "list-item message-item error-text";
                msg.textContent = "Bu il için ilçe kaydı bulunamadı.";
                list.appendChild(msg);
                return;
            }

            for (const district of rows) {
                const item = document.createElement("div");
                item.className = "list-item";
                item.textContent = district.name;
                item.tabIndex = 0;
                item.setAttribute("role", "button");
                item.dataset.districtId = district.id;

                const activate = () => {
                    list.querySelectorAll(".list-item.active")
                        .forEach((el) => el.classList.remove("active"));

                    item.classList.add("active");

                    // KRİTİK: Burada artık hiçbir geocoding servisi çağrılmıyor.
                    // İlçe koordinatı sayfa açılırken yüklenen veri setinden doğrudan kullanılıyor.
                    goTo(
                        district.lon,
                        district.lat,
                        12.4,
                        `${district.name}, ${province.name}`
                    );

                    setStatus(
                        `${district.name} / ${province.name} • ${district.lat.toFixed(4)}, ${district.lon.toFixed(4)}`,
                        "normal",
                        true
                    );

                    if (isMobileLayout()) {
                        closeMobileSidebar();
                    }
                };

                item.addEventListener("click", activate);
                item.addEventListener("keydown", (event) => {
                    if (event.key === "Enter" || event.key === " ") {
                        event.preventDefault();
                        activate();
                    }
                });

                list.appendChild(item);
            }
        }

        function selectProvince(province) {
            if (!province) return;

            selectedProvince = province;
            $("province-search").value = province.name;
            $("province-search-wrap").classList.add("hidden");
            $("search-label").classList.add("hidden");

            $("p-name").textContent = `${province.name} İli Seçildi`;
            $("selected-province-title").classList.remove("hidden");

            $("sidebar").classList.remove("hidden");
            $("district-toggle").classList.remove("hidden");

            renderDistricts(province);
            closeMobileSidebar();
            resizeMapSoon();

            goTo(province.lon, province.lat, 8.4, `${province.name} İli`);
        }

        function resolveProvinceFromInput() {
            const raw = $("province-search").value;
            const key = searchKey(raw);

            if (!key) return;

            const exact = provincesByKey.get(key);
            if (exact) {
                selectProvince(exact);
                return;
            }

            const matches = provinces.filter((province) =>
                searchKey(province.name).startsWith(key)
            );

            if (matches.length === 1) {
                selectProvince(matches[0]);
                return;
            }

            setStatus("İl bulunamadı. Listeden bir il seçin.", "warning", true);
        }

        function resetPortal() {
            selectedProvince = null;

            $("province-search").value = "";
            $("province-search-wrap").classList.remove("hidden");
            $("search-label").classList.remove("hidden");
            $("selected-province-title").classList.add("hidden");

            $("sidebar").classList.add("hidden");
            $("sidebar").classList.remove("mobile-open");
            $("district-toggle").classList.add("hidden");
            $("district-toggle").setAttribute("aria-expanded", "false");
            $("district-toggle").textContent = "☰ İlçeler";
            $("sidebar-backdrop").classList.remove("active");

            $("district-list").innerHTML = "";
            $("district-count").textContent = "0";

            if (activeMarker) {
                activeMarker.remove();
                activeMarker = null;
            }

            if (map && mapReady) {
                map.flyTo({
                    center: CONFIG.turkeyCenter,
                    zoom: CONFIG.turkeyZoom,
                    essential: true
                });
                resizeMapSoon();
            }

            setTimeout(() => $("province-search").focus(), 40);
        }

        function isMobileLayout() {
            return window.matchMedia("(max-width: 700px)").matches;
        }

        function openMobileSidebar() {
            if (!isMobileLayout()) return;
            $("sidebar").classList.add("mobile-open");
            $("sidebar-backdrop").classList.add("active");
            $("district-toggle").setAttribute("aria-expanded", "true");
            $("district-toggle").textContent = "✕ Kapat";
        }

        function closeMobileSidebar() {
            $("sidebar").classList.remove("mobile-open");
            $("sidebar-backdrop").classList.remove("active");
            $("district-toggle").setAttribute("aria-expanded", "false");
            $("district-toggle").textContent = "☰ İlçeler";
        }

        function syncResponsiveState() {
            if (!isMobileLayout()) {
                closeMobileSidebar();
            }
            resizeMapSoon();
        }

        async function startApplication() {
            setStatus("Harita ve ilçe merkez koordinatları yükleniyor...");

            const mapLibreOk = await ensureMapLibre();

            if (mapLibreOk) {
                initMap();
            } else {
                setStatus(
                    "MapLibre yüklenemedi. İnternet/CDN erişimini kontrol edin.",
                    "error"
                );
            }

            try {
                const data = await loadAdministrativeData();

                provinces = data.provinces;
                districts = data.districts;

                buildIndexes();
                populateProvinceOptions();

                $("data-badge").textContent =
                    `${provinces.length} il • ${districts.length} ilçe • ${data.source}`;
                $("data-badge").classList.remove("hidden");

                if (provinces.length !== 81 || districts.length !== 973) {
                    console.warn(
                        `Veri sayısı beklenenden farklı: ${provinces.length} il / ${districts.length} ilçe`
                    );
                }

                if (mapReady) {
                    hideStatus();
                } else {
                    setStatus(
                        `${provinces.length} il ve ${districts.length} ilçe koordinatı hazır. Harita bekleniyor...`,
                        "normal"
                    );
                }
            } catch (error) {
                console.error("İdari konum verileri yüklenemedi:", error);
                $("province-search").placeholder = "Konum verileri yüklenemedi";
                $("province-search").disabled = true;

                setStatus(
                    "İlçe merkez koordinatları yüklenemedi. Veri aynalarına erişim engellenmiş olabilir.",
                    "error"
                );
            }
        }

        document.addEventListener("DOMContentLoaded", () => {
            $("province-search").addEventListener("change", resolveProvinceFromInput);

            $("province-search").addEventListener("keydown", (event) => {
                if (event.key === "Enter") {
                    event.preventDefault();
                    resolveProvinceFromInput();
                }
            });

            $("selected-province-title").addEventListener("click", resetPortal);

            $("district-toggle").addEventListener("click", () => {
                if ($("sidebar").classList.contains("mobile-open")) {
                    closeMobileSidebar();
                } else {
                    openMobileSidebar();
                }
            });

            $("sidebar-backdrop").addEventListener("click", closeMobileSidebar);

            document.addEventListener("keydown", (event) => {
                if (event.key === "Escape") {
                    if ($("sidebar").classList.contains("mobile-open")) {
                        closeMobileSidebar();
                    } else if (selectedProvince) {
                        resetPortal();
                    }
                }
            });

            window.addEventListener("resize", syncResponsiveState);
            window.addEventListener("orientationchange", syncResponsiveState);

            startApplication();
        });
    </script>
</body>
</html>