<?php
header('Content-Type: text/html; charset=utf-8');

$DB_HOST='127.0.0.1'; $DB_NAME='shopeg.cn'; $DB_USER='shopeg.cn'; $DB_PASS='ShopEg2026!';
try {
  $db = new PDO("mysql:host=$DB_HOST;dbname=$DB_NAME;charset=utf8mb4", $DB_USER, $DB_PASS,
        [PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC]);
} catch (Exception $e) { die('db error'); }
function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }

/* ---------------- AJAX ---------------- */
if (isset($_GET['ajax'])) {
  header('Content-Type: application/json; charset=utf-8');
  $mode    = $_GET['mode'] ?? 'cities';
  $country = trim((string)($_GET['country'] ?? ''));
  $city    = trim((string)($_GET['city'] ?? ''));
  $belt    = trim((string)($_GET['belt'] ?? ''));
  $cat     = trim((string)($_GET['cat'] ?? ''));
  $q       = trim((string)($_GET['q'] ?? ''));

  $w = "lat IS NOT NULL AND lng IS NOT NULL";
  if ($country !== '') $w .= " AND country = " . $db->quote($country);
  if ($city    !== '') $w .= " AND (city_cn LIKE " . $db->quote('%'.$city.'%') . " OR prov LIKE " . $db->quote('%'.$city.'%') . ")";
  if ($belt    !== '') $w .= " AND cluster LIKE " . $db->quote('%'.$belt.'%');
  if ($cat     !== '') $w .= " AND cat1 = " . $db->quote($cat);
  if ($q       !== '') $w .= " AND name LIKE " . $db->quote('%'.$q.'%');

  function cache_get($k,$ttl){ $f='/tmp/mapf_cache/'.md5($k).'.json'; if(is_file($f) && time()-filemtime($f)<$ttl) return @file_get_contents($f); return null; }
  function cache_put($k,$s){ @mkdir('/tmp/mapf_cache',0777,true); @file_put_contents('/tmp/mapf_cache/'.md5($k).'.json',$s); }

  if ($mode === 'meta') {
    $f = __DIR__.'/map_cache_meta.json';
    if (is_file($f) && time()-filemtime($f) < 604800) { echo file_get_contents($f); exit; }
    $ck = 'meta';
    if ($c = cache_get($ck, 300)) { echo $c; exit; }
    $out = ['ok'=>1];
    $out['countries'] = $db->query("SELECT country, COUNT(*) c FROM fc_sup WHERE country IS NOT NULL AND country<>'' GROUP BY country ORDER BY c DESC")->fetchAll();
    $out['cities']    = $db->query("SELECT city_cn, COUNT(*) c FROM fc_sup WHERE city_cn IS NOT NULL AND city_cn<>'' GROUP BY city_cn ORDER BY c DESC LIMIT 600")->fetchAll();
    $out['belts']     = $db->query("SELECT cluster, COUNT(*) c FROM fc_sup WHERE cluster IS NOT NULL AND cluster<>'' GROUP BY cluster ORDER BY c DESC LIMIT 400")->fetchAll();
    $out['cats']      = $db->query("SELECT cat1, COUNT(*) c FROM fc_sup WHERE cat1 IS NOT NULL AND cat1<>'' GROUP BY cat1 ORDER BY c DESC LIMIT 40")->fetchAll();
    $out['total']     = (int)$db->query("SELECT COUNT(*) FROM fc_sup WHERE lat IS NOT NULL AND lng IS NOT NULL")->fetchColumn();
    $out['cities_n']  = (int)$db->query("SELECT COUNT(DISTINCT city_cn) FROM fc_sup WHERE lat IS NOT NULL AND city_cn IS NOT NULL AND city_cn<>''")->fetchColumn();
    $s = json_encode($out, JSON_UNESCAPED_UNICODE);
    cache_put($ck, $s); echo $s; exit;
  }

  if ($mode === 'cities') {
    $plain = ($city==='' && $belt==='' && $cat==='' && $q==='');
    if ($plain && $country==='') {
      $f = __DIR__.'/map_cache_cities_all.json';
      if (is_file($f) && time()-filemtime($f) < 604800) { echo file_get_contents($f); exit; }
    }
    if ($plain && $country==='CN') {
      $f = __DIR__.'/map_cache_cities_cn.json';
      if (is_file($f) && time()-filemtime($f) < 604800) { echo file_get_contents($f); exit; }
    }
    $ck = 'cities|'.$country.'|'.$city.'|'.$belt.'|'.$cat.'|'.$q;
    if ($c = cache_get($ck, 180)) { echo $c; exit; }
    $sql = "SELECT city_cn city, MAX(prov) prov, COUNT(*) c, AVG(lat) lat, AVG(lng) lng
            FROM fc_sup WHERE $w AND city_cn IS NOT NULL AND city_cn<>''
            GROUP BY city_cn ORDER BY c DESC LIMIT 500";
    $rows = $db->query($sql)->fetchAll();
    $total = (int)$db->query("SELECT COUNT(*) FROM fc_sup WHERE $w")->fetchColumn();
    $s = json_encode(['ok'=>1,'total'=>$total,'cities'=>$rows], JSON_UNESCAPED_UNICODE);
    cache_put($ck, $s); echo $s; exit;
  }

  if ($mode === 'points') {
    $lim = max(50, min(3000, (int)($_GET['limit'] ?? 2600)));
    $files = [];
    if ($city !== '') {
      $cf = __DIR__.'/map_pts/c_'.md5($city).'.json';
      if (is_file($cf)) $files = [$cf];
    }
    if (!$files) { $files = glob(__DIR__.'/map_pts/c_*.json'); }
    $acc = [];
    foreach ($files as $f) {
      $arr = json_decode(@file_get_contents($f), true);
      if (!$arr) continue;
      foreach ($arr as $p) {
        if ($city !== '' && is_file($cf) === false && stripos((string)($p['c'] ?? ''), $city) === false) continue;
        if ($belt !== '' && stripos((string)($p['cluster'] ?? ''), $belt) === false) continue;
        if ($cat  !== '' && (string)($p['cat_zh'] ?? '') !== $cat) continue;
        if ($q    !== '' && stripos((string)($p['name'] ?? ''), $q) === false) continue;
        $acc[] = $p;
        if (count($acc) >= $lim) break 2;
      }
    }
    echo json_encode(['ok'=>1,'n'=>count($acc),'src'=>'static','points'=>$acc], JSON_UNESCAPED_UNICODE); exit;
  }
  echo json_encode(['ok'=>0,'msg'=>'unknown mode']); exit;
}

$__tpl = @file_get_contents(__DIR__.'/tpl_top.html'); /* canonfix */
$__canon='https://shopeg.cn/factory_map.php';
$__tpl=preg_replace('/<link rel="canonical" href="[^"]*">/','<link rel="canonical" href="'.$__canon.'">',$__tpl,1);
if ($__tpl) { echo str_replace('__TITLE__', 'Factory Map · 地图选厂 | ShopEg', $__tpl); }
?>
<style>
.mapwrap{background:#dfe6ee;position:relative}
.mhero{padding:16px 0 14px;background:linear-gradient(180deg,#fff 0%,#f2f6fb 100%);color:#0b1b33;border-bottom:1px solid #e3e9f1;position:relative}
.mhero:before{content:'';position:absolute;left:0;top:16px;bottom:14px;width:4px;background:linear-gradient(180deg,#F4A51C,#DE961A);border-radius:0 3px 3px 0}
.mhero .wrap{display:flex;align-items:flex-end;justify-content:space-between;gap:20px;flex-wrap:wrap}
.mhero h1{font-size:26px;font-weight:800;letter-spacing:.5px;margin:0;color:#0b1b33}
.mhero h1 em{color:#d9870f;font-style:normal}
.mhero p{margin:5px 0 0;color:#6b7787;font-size:13.5px}
.mstat{display:flex;gap:22px}
.mstat div{text-align:right}
.mstat b{display:block;font-size:20px;color:#d9870f;font-weight:800;line-height:1.1}
.mstat span{font-size:11.5px;color:#8792a3;letter-spacing:.5px;font-weight:600}

.mbar{background:#fff;border-bottom:1px solid #e6eaf0;position:sticky;top:0;z-index:60;box-shadow:0 2px 10px rgba(9,33,67,.06)}
.mbar .wrap{display:flex;align-items:center;gap:8px;padding:8px 10px 8px 0;flex-wrap:wrap}
.mbar select,.mbar input{height:38px;border:1px solid #dfe5ee;border-radius:8px;padding:0 11px;font-size:13.5px;color:#12233d;background:#fff;outline:none;font-family:inherit}
.mbar select:focus,.mbar input:focus{border-color:var(--gold);box-shadow:0 0 0 3px rgba(244,165,28,.15)}
.mbar .f-lab{font-size:11.5px;color:#7c8798;margin:0 0 0 2px;white-space:nowrap}
.mbar .fld{display:flex;flex-direction:column;gap:2px}
.mbar .btn-go{height:38px;padding:0 20px;border:0;border-radius:8px;background:var(--gold);color:#0b1b33;font-weight:800;font-size:13.5px;cursor:pointer;letter-spacing:.5px}
.mbar .btn-go:hover{background:var(--gold-dark)}
.mbar .btn-rst{height:38px;padding:0 14px;border:1px solid #dfe5ee;border-radius:8px;background:#fff;color:#5b6778;font-size:13px;cursor:pointer}
.mbar .cnt{margin-left:auto;font-size:12px;color:#7c8798;white-space:nowrap}
.mbar .cnt b{color:var(--navy);font-size:15px}

#pano{position:absolute;right:0;top:0;bottom:0;width:46%;max-width:560px;min-width:300px;background:#fff;box-shadow:-10px 0 34px rgba(9,33,67,.2);z-index:1100;display:none;flex-direction:column}
#pano.on{display:flex}
#pano .h2{display:flex;align-items:center;gap:8px;padding:9px 12px;border-bottom:1px solid #e6ebf1;font-size:12.5px;color:#3c4a5c;font-weight:700}
#pano .h2 .x{margin-left:auto;cursor:pointer;color:#8792a3;font-size:16px;line-height:1;padding:2px 6px}
#pano .acts{display:flex;gap:6px;padding:8px 12px;border-bottom:1px solid #eef1f5}
#pano .acts a{flex:1;text-align:center;font-size:11.5px;padding:7px 4px;border-radius:7px;background:#f2f6fb;color:#1e6fd9;text-decoration:none;font-weight:700}
#pano .acts a.g{background:#092143;color:#fff}
#pano .body{flex:1;position:relative;display:flex}
#pano .body .ph{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;text-align:center;color:#94a0b0;font-size:12px;line-height:1.7;pointer-events:none}
#pano .body iframe{flex:1;border:0;width:100%;height:100%;background:transparent;position:relative;z-index:2}
#pano .fb{font-size:11px;color:#8792a3;padding:6px 12px;background:#f7f9fc;border-top:1px solid #eef1f5;line-height:1.5}
.pbtns{display:flex;gap:6px;margin-bottom:8px}
.pbtns a{flex:1;text-align:center;font-size:11.5px;font-weight:700;padding:7px 4px;border-radius:7px;text-decoration:none;background:#f2f6fb;color:#1e6fd9}
.pbtns a.sv{background:#0e3060;color:#fff}
.mapbox{position:relative;height:calc(100vh - 290px);min-height:560px;width:100%;background:#dfe9f3}
#mapA,#mapB{position:absolute;inset:0;width:100%;height:100%}
.mlayers{position:absolute;right:14px;top:14px;z-index:400;display:flex;gap:6px;background:rgba(255,255,255,.94);padding:5px;border-radius:10px;box-shadow:0 6px 20px rgba(9,33,67,.16)}
.mlayers button{border:0;background:transparent;font-size:12px;padding:6px 10px;border-radius:7px;cursor:pointer;color:#44506397;color:#445063}
.mlayers button.on{background:var(--navy);color:#fff;font-weight:700}
.legend{position:absolute;left:14px;bottom:14px;z-index:400;background:rgba(255,255,255,.94);padding:9px 12px;border-radius:10px;font-size:11.5px;color:#5b6778;box-shadow:0 6px 20px rgba(9,33,67,.14);line-height:1.7}
.legend i{display:inline-block;width:10px;height:10px;border-radius:50%;background:var(--gold);margin-right:5px;vertical-align:middle}
.legend i.sq{background:#1e6fd9;border-radius:2px}
.beltip{background:rgba(255,255,255,.96)!important;border:1px solid #dde4ee!important;border-radius:9px!important;padding:4px 9px!important;font-size:10.5px!important;color:#42506a!important;box-shadow:0 6px 18px rgba(9,33,67,.14)!important;white-space:nowrap!important;line-height:1.45!important}
.beltip b{color:#0b1b33;font-weight:800}
.beltip:before,.beltip:after{display:none!important}
.legend i.bl{background:linear-gradient(135deg,#cfe4f5,#f7d5e0,#d3ecd7);border:1px solid #9fb8cf}
.mtip{position:absolute;left:50%;top:74px;transform:translateX(-50%);z-index:500;background:#092143;color:#fff;padding:8px 16px;border-radius:22px;font-size:12.5px;box-shadow:0 8px 24px rgba(9,33,67,.28);display:none}
.mtip.on{display:block}

.pop{width:250px}
.pop .ph{display:flex;gap:10px;align-items:center;margin-bottom:8px}
.pop .ph img,.pop .ph .ph0{width:46px;height:46px;border-radius:8px;object-fit:contain;background:#f5f7fa;border:1px solid #eef1f5;display:flex;align-items:center;justify-content:center;font-weight:800;color:#9aa6b5;font-size:18px}
.pop .nm{font-weight:800;font-size:13.5px;color:#0b1b33;line-height:1.35;max-height:38px;overflow:hidden}
.pop .lc{font-size:11.5px;color:#8792a3;margin-top:2px}
.pop .tags{display:flex;flex-wrap:wrap;gap:5px;margin:7px 0 8px}
.pop .tg{font-size:10.5px;padding:2px 7px;border-radius:5px;background:#eef3fb;color:#1e6fd9}
.pop .tg.g{background:#fdf3e2;color:#b5761a}
.pop .mt{font-size:11.5px;color:#5b6778;line-height:1.65;margin-bottom:6px}
.pop .acc{font-size:10.5px;color:#9aa6b5;margin-bottom:8px}
.pop a.go{display:block;text-align:center;background:#092143;color:#fff;text-decoration:none;font-size:12.5px;font-weight:700;padding:8px;border-radius:7px}
.pop a.go:hover{background:#0e3060}

.cityb{background:#092143;color:#fff;border-radius:50%;display:flex;align-items:center;justify-content:center;font-weight:800;box-shadow:0 4px 14px rgba(9,33,67,.35);border:2px solid rgba(244,165,28,.85)}
.fc{background:linear-gradient(160deg,#F4A51C,#DE961A);color:#0b1b33;border-radius:50%;display:flex;align-items:center;justify-content:center;font-weight:800;border:2px solid #fff;box-shadow:0 3px 10px rgba(180,110,10,.38)}
.pin{width:14px;height:14px;border-radius:50%;background:var(--gold);border:2px solid #fff;box-shadow:0 2px 6px rgba(9,33,67,.4)}

.leaflet-popup-content{margin:12px 14px}
@media(max-width:820px){
  .mhero{padding:12px 0 10px}
  .mhero h1{font-size:20px}
  .mhero p{display:none}
  .mstat{gap:12px}
  .mstat b{font-size:16px}
  .mstat span{font-size:10px}
  .mapbox{height:calc(100vh - 220px);min-height:460px}
  #pano{width:100%;max-width:none;min-width:0}
  #pano .h2,#pano .acts{padding:7px 10px}
  .mbar{position:static}
  .mbar .wrap{flex-wrap:nowrap;overflow-x:auto;-webkit-overflow-scrolling:touch;gap:6px;padding:6px 0}
  .mbar .wrap::-webkit-scrollbar{display:none}
  .mbar .fld{flex:0 0 auto}
  .mbar .f-lab{display:none}
  .mbar select,.mbar input{height:32px;font-size:12px}
  .mbar .btn-go{height:32px;padding:0 12px;flex:0 0 auto;position:sticky;right:0;box-shadow:-10px 0 14px rgba(255,255,255,.95)}
  .mbar .btn-rst{height:32px;padding:0 10px;flex:0 0 auto}
  .mbar .cnt{display:none}
  .legend{display:none}
  .mlayers{right:10px;top:10px;padding:4px;flex-wrap:wrap;max-width:calc(100% - 20px)}
  .mlayers button{padding:5px 8px;font-size:11px}
}
</style>
<style>
/* 2026-11-29 地图页：页眉保留不动，只压缩标题与筛选栏，地图吃满剩余高度 */
.mhero{padding:10px 0 8px!important}
.mhero h1{font-size:21px!important}
.mhero p{display:none!important}
.mhero .mstat b{font-size:17px!important}
.mhero .mstat span{font-size:9.5px!important}
.mbar .wrap{display:flex!important;flex-wrap:nowrap!important;gap:6px!important;padding:7px 10px!important;overflow-x:auto!important;align-items:center!important}
.mbar .fld{flex-direction:row!important;align-items:center!important;gap:5px!important;flex:0 0 auto!important}
.mbar .f-lab{font-size:11px!important;margin:0!important;color:#8b95a5!important}
.mbar select,.mbar input{height:31px!important;font-size:12.5px!important;border-radius:6px!important;padding:0 8px!important}
.mbar .btn-go,.mbar .btn-rst{height:31px!important;font-size:12.5px!important;padding:0 13px!important;flex:0 0 auto!important}
.mbar .cnt{margin-left:auto!important;font-size:11.5px!important;flex:0 0 auto!important}
.mapbox{height:calc(100vh - 335px)!important;min-height:600px!important}
@media(max-width:900px){.mapbox{height:calc(100vh - 270px)!important;min-height:430px!important}}
</style>
<style>
/* 地图页一屏：整页不滚动，地图填满剩余高度 */
html,body{height:auto!important;min-height:100%!important;overflow-x:hidden!important}
.mapbox{height:calc(100vh - 320px)!important;min-height:420px!important}
</style>
<style>
/* 右侧工厂列表（缩放≥8 才出现） */
.frail{position:absolute;right:12px;top:12px;bottom:12px;width:322px;background:#fff;border:1px solid #e3e8f0;
 border-radius:12px;box-shadow:0 10px 30px rgba(9,33,67,.14);display:none;flex-direction:column;z-index:900;overflow:hidden}
.frail.on{display:flex}
.frail .fh{display:flex;align-items:center;gap:8px;padding:10px 12px;border-bottom:1px solid #eef1f6;background:#f8fafd}
.frail .fh b{font-size:13px;color:#092143}
.frail .fh span{font-size:12px;color:#7d8798;margin-left:auto}
.frail .fh i{cursor:pointer;font-style:normal;color:#9aa4b5;font-size:14px;padding:0 2px}
.flist{flex:1;overflow-y:auto;overscroll-behavior:contain}
.fcard{display:flex;gap:10px;padding:10px 12px;border-bottom:1px solid #f1f4f9;text-decoration:none;cursor:pointer}
.fcard:hover{background:#f6f9ff}
.fcard img,.fcard .fb0{width:46px;height:46px;border-radius:8px;object-fit:contain;border:1px solid #eef1f6;flex:0 0 46px;background:#fff}
.fcard .fb0{display:flex;align-items:center;justify-content:center;background:#eef3fb;color:#4a6da8;font-weight:800;font-size:16px}
.fcard .fi{min-width:0;flex:1}
.fcard .fn{font-size:13px;font-weight:700;color:#13233d;line-height:1.35;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}
.fcard .fc{display:inline-block;margin-top:3px;font-size:11px;color:#3f6ea8;background:#eef4fc;border-radius:10px;padding:1px 7px}
.fcard .fp{margin-top:4px;font-size:11.5px;color:#7b8697;line-height:1.35;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}
.frail .fe{padding:26px 16px;text-align:center;color:#8b95a5;font-size:12.5px;line-height:1.6}
.frail .ff{padding:8px 12px;border-top:1px solid #eef1f6;font-size:11px;color:#94a0b2;background:#fafcff}
#fr-tg{position:absolute;right:12px;top:12px;z-index:901;display:none;width:34px;height:34px;border-radius:9px;border:1px solid #dfe5ee;
 background:#fff;box-shadow:0 4px 12px rgba(9,33,67,.12);cursor:pointer;font-size:15px;color:#34496b}
@media(max-width:900px){.frail{width:calc(100% - 20px);left:10px;right:10px;top:auto;height:44%;bottom:10px}}
.mlayers{left:56px!important;right:auto!important;top:12px!important}
</style>



<?php require __DIR__ . '/_site_chrome.php'; site_css(); ?>
<div class="mapwrap">
  <section class="mhero">
    <div class="wrap">
      <div>
        <h1>Factory <em>Map</em> · 地图选厂</h1>
        <p>Pick a country, a city or an industrial belt — see exactly where the factories are, then open their profiles.</p>
      </div>
      <div class="mstat">
        <div><b id="st-total">0</b><span>FACTORIES</span></div>
        <div><b id="st-cities">0</b><span>CITIES</span></div>
        <div><b id="st-shown">0</b><span>ON MAP</span></div>
      </div>
    </div>
  </section>

  <div class="mbar">
    <div class="wrap">
      <div class="fld"><span class="f-lab">Country 国家</span>
        <select id="f-country" style="min-width:132px"><option value="">All countries</option></select>
      </div>
      <div class="fld"><span class="f-lab">City 城市</span>
        <input id="f-city" list="dl-city" placeholder="e.g. Shenzhen / 深圳" style="width:158px">
        <datalist id="dl-city"></datalist>
      </div>
      <div class="fld"><span class="f-lab">Industrial belt 产业带</span>
        <input id="f-belt" list="dl-belt" placeholder="e.g. 佛山·家具" style="width:150px">
        <datalist id="dl-belt"></datalist>
      </div>
      <div class="fld"><span class="f-lab">Product type 产品类型</span>
        <select id="f-cat" style="min-width:132px"><option value="">All types</option></select>
      </div>
      <div class="fld"><span class="f-lab">Factory name 厂家名称</span>
        <input id="f-q" placeholder="e.g. Textile" style="width:150px">
      </div>
      <button class="btn-go" id="btn-go">Search</button>
      <button class="btn-rst" id="btn-rst">Reset</button>
      <div class="cnt"><b id="cnt-total">0</b><span id="cnt-city"></span></div>
    </div>
  </div>

  <div style="position:relative">
    <div class="mapbox">
      <div id="mapA"></div>
      <div id="mapB" style="display:none"></div>
    </div>
    <div class="mlayers">
      <button data-l="amap" class="on">Map</button>
      <button data-l="google">Google</button>
      <button data-l="baidu">百度</button>
      <button data-l="sat">Satellite</button>
      <button data-b="1" class="on">产业带</button>
      <button data-p="1" id="btn-pano">Panorama</button>
    </div>
    <div class="legend"><div><i></i>城市聚类（点开看工厂）</div><div><i class="sq"></i>单个工厂</div><div><i class="bl"></i>产业带色块（悬停看名称）</div></div>
    <button id="fr-tg" title="Factories 工厂列表">▤</button>
    <div class="frail" id="frail">
      <div class="fh"><b>Factories in view 视野内工厂</b><span id="fr-n"></span><i id="fr-x">✕</i></div>
      <div class="flist" id="fr-list"></div>
      <div class="ff">Zoom in to see factories · 放大地图后逐条加载</div>
    </div>
    <div class="mtip" id="mtip">Loading…</div>
    <div id="pano">
      <div class="h2"><span id="pano-tt">Street View 街景</span><span class="x" id="pano-x">✕</span></div>
      <div class="acts">
        <a class="g" id="pano-g" target="_blank" rel="noopener">Google 全景 ↗</a>
        <a id="pano-b" target="_blank" rel="noopener">百度地图 ↗</a>
        <a id="pano-c">关闭</a>
      </div>
      <div class="body"><div class="ph">街景加载中…<br>若此处空白，请点上方「Google 全景 ↗」在新标签打开</div>
      <iframe id="pano-f" src="about:blank" allowfullscreen referrerpolicy="no-referrer-when-downgrade"></iframe></div>
      <div class="fb" id="pano-fb">全景为空或加载不出时，点上面「Google 全景 ↗」在新标签打开（Google 街景覆盖更全）。位置为城市级近似，可能不在该厂门口。</div>
    </div>
  </div>
</div>

<link rel="stylesheet" href="/vendor/leaflet/leaflet.css">
<link rel="stylesheet" href="/vendor/leaflet/MarkerCluster.css">
<link rel="stylesheet" href="/vendor/leaflet/MarkerCluster.Default.css">
<script src="/vendor/leaflet/leaflet.js"></script>
<script src="/vendor/leaflet/leaflet.markercluster.js"></script>
<script src="/vendor/leaflet/proj4.js"></script>
<script src="/vendor/leaflet/proj4leaflet.js"></script>
<script src="/vendor/leaflet/chinese-providers.js"></script>
<script>
(function(){
  var API=<?= json_encode($_SERVER['SCRIPT_NAME'], JSON_UNESCAPED_UNICODE) ?>;
  var X_PI=Math.PI*3000/180;
  function toBD(lat,lng){
    var x=lng,y=lat,z=Math.sqrt(x*x+y*y)+0.00002*Math.sin(y*X_PI),
        th=Math.atan2(y,x)+0.000003*Math.cos(x*X_PI);
    return [z*Math.sin(th)+0.006, z*Math.cos(th)+0.0065];
  }

  var mapA=L.map('mapA',{zoomControl:true,minZoom:3,maxZoom:19,worldCopyJump:true}).setView([33.6,110.5],4);
  var mapB=L.map('mapB',{crs:L.CRS.Baidu,zoomControl:false,minZoom:3,maxZoom:18}).setView([33.6,110.5],5);
  var baseA={
    amap:L.tileLayer('https://webrd0{s}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}',{maxZoom:18,subdomains:['1','2','3','4'],attribution:'© 高德'}),
    google:L.tileLayer('https://mt{s}.google.com/vt/lyrs=m&hl=zh-CN&x={x}&y={y}&z={z}',{maxZoom:20,subdomains:['0','1','2','3'],attribution:'© Google'}),
    sat:L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',{maxZoom:18,attribution:'© Esri'})
  };
  var baseB=L.tileLayer.chinaProvider('Baidu.Normal.Map',{maxZoom:18,minZoom:3,attribution:'© 百度地图'});
  var baseBLoaded=false;
  var curBase='amap', curMode='A';
  window.__mA=mapA; window.__mB=mapB;
  baseA.amap.addTo(mapA);

  function curMap(){ return curMode==='B'?mapB:mapA; }
  function conv(){ return curMode==='B'?toBD:function(a,b){return [a,b];}; }

  var clusterOpt={showCoverageOnHover:false,maxClusterRadius:52,disableClusteringAtZoom:9,
    iconCreateFunction:function(cl){
      var n=cl.getChildCount();
      var s=n>=400?54:(n>=150?46:(n>=60?38:(n>=25?32:28)));
      return L.divIcon({html:'<div class="cityb" style="width:'+s+'px;height:'+s+'px;font-size:'+(s>=38?14:12)+'px">'+n+'</div>',className:'',iconSize:[s,s]});
    }};
  var facOpt={showCoverageOnHover:false,maxClusterRadius:42,disableClusteringAtZoom:15,
    iconCreateFunction:function(cl){
      var n=cl.getChildCount();
      var s=n>=500?50:(n>=200?43:(n>=60?36:29));
      return L.divIcon({html:'<div class="fc" style="width:'+s+'px;height:'+s+'px;font-size:'+(s>=36?13:11)+'px">'+n+'</div>',className:'',iconSize:[s,s]});
    }};
  var cityA=L.markerClusterGroup(clusterOpt).addTo(mapA);
  var cityB=L.markerClusterGroup(clusterOpt).addTo(mapB);
  var facA=L.markerClusterGroup(facOpt).addTo(mapA);
  var facB=L.markerClusterGroup(facOpt).addTo(mapB);
  function cityGrp(){ return curMode==='B'?cityB:cityA; }
  function facGrp(){ return curMode==='B'?facB:facA; }

  var beltA=L.layerGroup().addTo(mapA);
  var beltB=L.layerGroup().addTo(mapB);
  function beltGrp(){ return curMode==='B'?beltB:beltA; }
  var beltOn=true;
  var BCOL=[
    {s:'#2f78b5',f:'#8ec4e8'},{s:'#b04f77',f:'#f0a2b8'},{s:'#3f8a55',f:'#94ce9d'},{s:'#624fa0',f:'#b3a2e0'},
    {s:'#b06f22',f:'#f2bc85'},{s:'#8c8622',f:'#ddd77a'},{s:'#248380',f:'#86d0cb'},{s:'#a44a3f',f:'#e8a196'},
    {s:'#40519c',f:'#a2aee0'},{s:'#547a3a',f:'#bfd98e'},{s:'#95407d',f:'#e89fcf'},{s:'#7d5f3c',f:'#cfb491'}
  ];
  var state={cities:[],pts:[],belts:[],facOn:false};

  function markBtn(k){
    document.querySelectorAll('.mlayers button[data-l]').forEach(function(b){ b.classList.toggle('on', b.dataset.l===k); });
  }
  function redraw(){
    paintCities(); paintBelts(); paintPts();
  }
  function setMode(m){
    if(m===curMode) return;
    var c=curMap().getCenter(), z=curMap().getZoom();
    if(m==='B'){
      if(!baseBLoaded){ baseB.addTo(mapB); baseBLoaded=true; }
      document.getElementById('mapA').style.display='none';
      document.getElementById('mapB').style.display='block';
      mapB.invalidateSize();
      mapB.setView(toBD(c.lat,c.lng), Math.min(z+1,18));
    } else {
      document.getElementById('mapB').style.display='none';
      document.getElementById('mapA').style.display='block';
      mapA.invalidateSize();
      mapA.setView([c.lat,c.lng], Math.max(z-1,3));
    }
    curMode=m;
    redraw();
  }
  function showBase(k){
    if(k==='baidu'){ setMode('B'); markBtn('baidu'); return; }
    if(curMode==='B'){ setMode('A'); }
    if(curBase!==k && baseA[k]){ mapA.removeLayer(baseA[curBase]); baseA[k].addTo(mapA); curBase=k; }
    markBtn(k);
  }
  document.querySelectorAll('.mlayers button[data-l]').forEach(function(btn){
    btn.addEventListener('click',function(){
      var k=btn.dataset.l; if(k===curBase && curMode!=='B') return;
      if(panoMode){ panoMode=false; panoBtn.classList.remove('on'); curMap().getContainer().style.cursor=''; closePano(); }
      showBase(k);
    });
  });

  document.querySelectorAll('.mlayers button[data-b]').forEach(function(btn){
    btn.addEventListener('click',function(){
      beltOn=!beltOn; btn.classList.toggle('on',beltOn); paintBelts();
    });
  });
  var reqSeq=0;
  var tip=document.getElementById('mtip');
  function showTip(t){tip.textContent=t;tip.classList.add('on');}
  function hideTip(){tip.classList.remove('on');}

  function params(extra){
    var p=new URLSearchParams({ajax:'1'});
    var c=document.getElementById('f-country').value,
        ci=document.getElementById('f-city').value.trim(),
        b=document.getElementById('f-belt').value.trim(),
        t=document.getElementById('f-cat').value.trim(),
        q=document.getElementById('f-q').value.trim();
    if(c)p.set('country',c); if(ci)p.set('city',ci); if(b)p.set('belt',b); if(t)p.set('cat',t); if(q)p.set('q',q);
    for(var k in extra) p.set(k,extra[k]);
    return p.toString();
  }
  function jit(p, spread){
    spread = spread || 0.008;
    var s=(p.id*1103515245+12345)>>>0;
    var a=((s%1000)/1000)*Math.PI*2;
    var r=0.0015+(((s>>10)%1000)/1000)*spread;
    return [p.lat+r*Math.sin(a), p.lng+r*Math.cos(a)*1.15];
  }
  function popupHtml(p){
    var nm=p.name||'—';
    var logo='<div class="ph0">'+nm.charAt(0).toUpperCase()+'</div>';
    var tags='';
    if(p.cat_zh) tags+='<span class="tg">'+p.cat_zh+'</span>';
    if(p.cluster) tags+='<span class="tg g">'+p.cluster+'</span>';
    var meta=[];
    if(p.area) meta.push('Area 面积: '+p.area);
    if(p.employees) meta.push('Staff 员工: '+p.employees);
    var loc=[p.c||'',p.p||''].filter(Boolean).join(' · ');
    return '<div class="pop"><div class="ph">'+logo+'<div><div class="nm">'+nm+'</div><div class="lc">'+loc+'</div></div></div>'
      +(tags?'<div class="tags">'+tags+'</div>':'')
      +(meta.length?'<div class="mt">'+meta.join('<br>')+'</div>':'')
      +'<div class="acc">Location ≈ city level 位置为城市级近似</div>'
      +'<div class="pbtns"><a class="sv" href="javascript:;" onclick="openPano('+p.lat+','+p.lng+')">Street View 全景</a>'
      +'<a target="_blank" rel="noopener" href="https://www.google.com/maps/@?api=1&map_action=pano&viewpoint='+p.lat+','+p.lng+'">Google 街景 ↗</a></div>'
      +'<a class="go" target="_blank" rel="noopener" href="/factory_profile.php?id='+p.id+'">View factory 查看工厂 →</a></div>';
  }

  var panoMode=false;
  var panoBox=document.getElementById('pano'),
      panoF=document.getElementById('pano-f'),
      panoT=document.getElementById('pano-tt');
  function openPano(lat,lng,label){
    panoT.textContent=label||('Street View · '+lat.toFixed(4)+','+lng.toFixed(4));
    document.getElementById('pano-g').href='https://www.google.com/maps/@?api=1&map_action=pano&viewpoint='+lat+','+lng;
    document.getElementById('pano-b').href='https://map.baidu.com/@'+lng+','+lat+',18z';
    if(curMode==='B'){
      panoF.src='https://map.baidu.com/@'+lng+','+lat+',17z';
      document.getElementById('pano-fb').innerHTML='当前为百度底图：框内是百度地图，点右上角「全景」图标即可进入百度街景。';
    } else {
      panoF.src='https://www.google.com/maps/embed?pb=!6m6!1m5!2m2!1d'+lng+'!2d'+lat+'!4f-0!5f1';
      document.getElementById('pano-fb').innerHTML='全景为空或加载不出时，点上面「Google 全景 ↗」在新标签打开（Google 街景覆盖更全）。位置为城市级近似，可能不在该厂门口。';
    }
    panoBox.classList.add('on');
    setTimeout(function(){ curMap().invalidateSize(); },320);
  }
  window.openPano=openPano;
  function closePano(){ panoBox.classList.remove('on'); panoF.src='about:blank'; setTimeout(function(){curMap().invalidateSize();},200); }
  document.getElementById('pano-x').onclick=closePano;
  document.getElementById('pano-c').onclick=closePano;
  var panoBtn=document.getElementById('btn-pano');
  panoBtn.addEventListener('click',function(){
    panoMode=!panoMode;
    panoBtn.classList.toggle('on',panoMode);
    curMap().getContainer().style.cursor=panoMode?'crosshair':'';
    if(!panoMode) closePano();
    else showTip('点击地图任意位置查看街景 · tap a spot for street view');
    if(panoMode) setTimeout(hideTip,2600);
  });
  function fromBD(lat,lng){
    var x=lng-0.0065, y=lat-0.006, z=Math.sqrt(x*x+y*y)-0.00002*Math.sin(y*X_PI),
        th=Math.atan2(y,x)-0.000003*Math.cos(x*X_PI);
    return [z*Math.sin(th), z*Math.cos(th)];
  }
  mapA.on('click',function(e){
    if(!panoMode) return;
    openPano(e.latlng.lat,e.latlng.lng,'Street View · zoom '+mapA.getZoom());
  });
  mapB.on('click',function(e){
    if(!panoMode) return;
    var g=fromBD(e.latlng.lat,e.latlng.lng);
    openPano(g[0],g[1],'Street View · zoom '+mapB.getZoom());
  });

  function paintCities(){
    cityGrp().clearLayers();
    var cv=conv(), list=state.cities||[];
    var max=1; list.forEach(function(c){ if(c.c>max) max=c.c; });
    list.forEach(function(c){
      if(!c.lat||!c.lng) return;
      var r=Math.round(12+Math.min(14, Math.sqrt(c.c/max)*14));
      var icon=L.divIcon({className:'',html:'<div class="cityb" style="width:'+r+'px;height:'+r+'px;font-size:'+(r>22?12:11)+'px">'+c.c+'</div>',iconSize:[r,r]});
      var ll=cv(c.lat,c.lng);
      var m=L.marker(ll,{icon:icon});
      m.bindTooltip(c.city+(c.prov?(' · '+c.prov):'')+' — '+c.c+' factories',{direction:'top',offset:[0,-4]});
      m.on('click',function(){ loadCityPoints(c.city); });
      cityGrp().addLayer(m);
    });
  }
  function paintBelts(){
    var grp=beltGrp(); grp.clearLayers();
    if(!beltOn) return;
    var m=curMap();
    var q1=m.containerPointToLatLng([10,10]), q2=m.containerPointToLatLng([110,10]);
    var mpp=q1.distanceTo(q2)/100 || 1000;
    var cv=conv(), list=state.belts||[];
    list.forEach(function(b,i){
      var col=BCOL[i%BCOL.length];
      var px = curMap().getZoom()<6 ? (b.c>=60?26:(b.c>=25?22:18)) : (b.c>=100?40:(b.c>=60?34:(b.c>=30?28:(b.c>=15?22:18))));
      var rad=px*mpp;
      var ll=cv(b.lat,b.lng);
      var rings=[[1,0.36,1.0],[0.60,0.54,0],[0.34,0.70,0]];
      rings.forEach(function(rg){
        grp.addLayer(L.circle(ll,{radius:rad*rg[0],color:col.s,weight:rg[2],opacity:rg[2]?0.55:0,
          fillColor:col.f,fillOpacity:rg[1],interactive:!!rg[2]}));
      });
      var cir=L.circle(ll,{radius:rad*0.72,color:col.s,weight:0,opacity:0,fillColor:col.f,fillOpacity:0.02});
      var sub=(b.others&&b.others.length)?('<br><span style="color:#8792a3">'+b.others.join(' / ')+'</span>'):'';
      cir.bindTooltip('<b>'+b.name+'</b> · '+b.c+' factories'+sub,
        {permanent:(curMap().getZoom()>=8),direction:(i%2?'bottom':'top'),className:'beltip',offset:[0,i%2?4:-2]});
      grp.addLayer(cir);
    });
  }
  function paintPts(){
    var grp=facGrp(); grp.clearLayers();
    var cv=conv(), pts=state.pts||[];
    if(!pts.length) return;
    var icon=L.divIcon({className:'',html:'<div class="pin"></div>',iconSize:[14,14],iconAnchor:[7,7]});
    var spread=pts.length>800?0.026:(pts.length>200?0.014:0.006);
    pts.forEach(function(p){
      var j=jit(p,spread);
      var m=L.marker(cv(j[0],j[1]),{icon:icon});
      m.bindPopup(popupHtml(p),{maxWidth:290,minWidth:250});
      grp.addLayer(m);
    });
  }

  function loadCities(){
    var seq=++reqSeq;
    showTip('Loading cities…');
    fetch(API+'?'+params({mode:'cities'}),{cache:'no-store'}).then(r=>r.json()).then(function(d){
      if(seq!==reqSeq) return;
      state.cities=d.cities||[];
      paintCities();
      document.getElementById('cnt-total').textContent=(d.total||0).toLocaleString();
      document.getElementById('cnt-city').textContent='';
      document.getElementById('st-shown').textContent=(d.cities||[]).length;
      hideTip();
    }).catch(hideTip);
  }

  var ptsCache={};
  function loadCityPoints(city, cb){
    showTip('Loading factories…');
    var done=function(pts){
      state.pts=pts;
      paintPts();
      document.getElementById('st-shown').textContent=pts.length;
      hideTip();
      if(cb) cb(pts);
    };
    if(ptsCache[city]) { done(ptsCache[city]); return; }
    fetch(API+'?'+params({mode:'points',city:city}),{cache:'no-store'})
      .then(r=>r.json()).then(function(d){ ptsCache[city]=d.points||[]; done(ptsCache[city]); })
      .catch(function(){ hideTip(); });
  }
  function zoomToCity(name, pts){
    if(!pts||!pts.length) return;
    var cv=conv();
    var bd=L.latLngBounds(pts.map(function(p){ var j=cv(p.lat,p.lng); return [j[0],j[1]]; }));
    curMap().fitBounds(bd.pad(0.12),{maxZoom:13});
  }

  function searchPoints(){
    showTip('Searching…');
    fetch(API+'?'+params({mode:'points',limit:2600}),{cache:'no-store'}).then(r=>r.json()).then(function(d){
      var pts=d.points||[];
      if(!pts.length){ hideTip(); return; }
      state.pts=pts;
      paintPts();
      document.getElementById('st-shown').textContent=pts.length;
      zoomToCity('', pts); hideTip();
    }).catch(hideTip);
  }

  function refresh(){ paintBelts(); if(curMap().getZoom()<9) loadCities(); frSchedule(); }


  /* ===== 右侧工厂列表：按视野 + 缩放级别加载 ===== */
  var frail=document.getElementById('frail'),
      frList=document.getElementById('fr-list'),
      frN=document.getElementById('fr-n'),
      frTg=document.getElementById('fr-tg'),
      frX=document.getElementById('fr-x');
  var frSeq=0, frClosed=false, frTimer=null, frLastKey='';

  function frEsc(t){ return (t||'').replace(/[&<>"]/g,function(c){return {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c];}); }
  function frKey(){
    var m=curMap(), b=m.getBounds();
    return m.getZoom()+'|'+[b.getWest(),b.getSouth(),b.getEast(),b.getNorth()].map(function(x){return x.toFixed(2)}).join(',')
      +'|'+document.getElementById('f-cat').value+document.getElementById('f-q').value
      +document.getElementById('f-belt').value+document.getElementById('f-city').value+document.getElementById('f-country').value;
  }
  function frRender(d){
    if(d.total===0){ frList.innerHTML='<div class="fe">No factory in this view.<br>本视野内没有工厂，拖动或缩小地图试试。</div>'; }
    else if(!d.factories.length){ frList.innerHTML='<div class="fe">Loading…</div>'; }
    else {
      var h='';
      d.factories.forEach(function(f){
        var logo=f.logo?('<img src="'+frEsc(f.logo)+'" loading="lazy" alt="">'):('<div class="fb0">'+(frEsc(f.name).charAt(0)||'F')+'</div>');
        h+='<a class="fcard" href="'+f.link+'">'+logo+'<div class="fi">'
          +'<div class="fn">'+frEsc(f.name)+'</div>'
          +(f.cat?('<span class="fc">'+frEsc(f.cat)+'</span>'):'')
          +(f.product?('<div class="fp">'+frEsc(f.product)+'</div>'):'')
          +'</div></a>';
      });
      frList.innerHTML=h;
    }
    frN.textContent=(d.total||0)+(d.total>d.factories.length?(' · top '+d.factories.length):'');
  }
  function frLoad(force){
    var m=curMap();
    if(m.getZoom()<8){ frail.classList.remove('on'); frTg.style.display='none'; return; }
    frTg.style.display=frClosed?'block':'none';
    if(frClosed) return;
    var key=frKey();
    if(!force && key===frLastKey) return;
    frLastKey=key;
    var b=m.getBounds();
    var seq=++frSeq;
    var u='/map_fact.php?act=inview&zoom='+m.getZoom()+'&limit=40&bbox='
      +encodeURIComponent([b.getWest(),b.getSouth(),b.getEast(),b.getNorth()].join(','))
      +'&'+params({});
    fetch(u,{cache:'no-store'}).then(function(r){return r.json()}).then(function(d){
      if(seq!==frSeq||!d||!d.ok) return;
      frail.classList.add('on');
      frList.scrollTop=0;
      frRender(d);
    }).catch(function(){});
  }
  function frSchedule(){ if(frTimer) clearTimeout(frTimer); frTimer=setTimeout(frLoad,340); }
  frX.addEventListener('click',function(){ frClosed=true; frail.classList.remove('on'); frTg.style.display='block'; });
  frTg.addEventListener('click',function(){ frClosed=false; frTg.style.display='none'; frLoad(true); });

  var t=null, zt=null;
  [mapA,mapB].forEach(function(m){
    m.on('moveend zoomend',function(){
      if(t) clearTimeout(t); t=setTimeout(refresh,320);
      m.getContainer().classList.toggle('beltlow', m.getZoom()<8);
    });
    m.on('zoomend',function(){ if(zt) clearTimeout(zt); zt=setTimeout(paintBelts,140); });
  });

  document.getElementById('btn-go').addEventListener('click',function(){
    var c=document.getElementById('f-city').value.trim();
    if(c){ loadCityPoints(c, function(pts){ zoomToCity(c, pts); }); }
    else if(document.getElementById('f-belt').value.trim() || document.getElementById('f-q').value.trim()){ searchPoints(); }
    else { refresh(); }
  });
  document.getElementById('btn-rst').addEventListener('click',function(){
    ['f-country','f-city','f-belt','f-cat','f-q'].forEach(function(id){document.getElementById(id).value='';});
    ptsCache={}; state.pts=[]; paintPts();
    document.getElementById('st-shown').textContent='—';
    if(curMode==='B') mapB.setView(toBD(33.6,110.5),5); else mapA.setView([33.6,110.5],4);
    refresh();
  });
  document.getElementById('f-country').addEventListener('change',function(){
    ptsCache={}; state.pts=[]; paintPts();
    refresh();
  });
  document.getElementById('f-cat').addEventListener('change',function(){ refresh(); });
  ['f-city','f-belt','f-q'].forEach(function(id){
    document.getElementById(id).addEventListener('keydown',function(e){ if(e.key==='Enter'){ e.preventDefault(); document.getElementById('btn-go').click(); } });
  });

  fetch('/map_belts.json',{cache:'no-store'}).then(function(r){return r.json();}).then(function(d){
    state.belts=d.belts||[]; paintBelts();
    mapA.getContainer().classList.toggle('beltlow', mapA.getZoom()<8);
    mapB.getContainer().classList.toggle('beltlow', mapB.getZoom()<8);
  }).catch(function(){});

  fetch(API+'?ajax=1&mode=meta',{cache:'no-store'}).then(r=>r.json()).then(function(d){
    document.getElementById('st-total').textContent=(d.total||0).toLocaleString();
    document.getElementById('st-cities').textContent=(d.cities_n||0).toLocaleString();
    var cs=document.getElementById('f-country');
    (d.countries||[]).forEach(function(x){
      var o=document.createElement('option'); o.value=x.country; o.textContent=x.country+' ('+x.c+')'; cs.appendChild(o);
    });
    cs.value='CN';
    var ct=document.getElementById('f-cat');
    (d.cats||[]).forEach(function(x){
      var o=document.createElement('option'); o.value=x.cat1; o.textContent=x.cat1+' ('+x.c+')'; ct.appendChild(o);
    });
    var dl1=document.getElementById('dl-city');
    (d.cities||[]).forEach(function(x){ var o=document.createElement('option'); o.value=x.city_cn; o.label=x.c+' factories'; dl1.appendChild(o); });
    var dl2=document.getElementById('dl-belt');
    (d.belts||[]).forEach(function(x){ var o=document.createElement('option'); o.value=x.cluster; o.label=x.c+' factories'; dl2.appendChild(o); });
    loadCities();
  }).catch(loadCities);
})();
</script>
<?php /* 地图页一屏铺满，页脚不输出，避免半屏滚动 */ ?>
<?php require_once __DIR__.'/_site_chrome.php'; site_foot(); ?>
