代码
const DATA = window.ZHANGJIANG_DATA;

const $ = (id) => document.getElementById(id);
const pad = (n) => String(n).padStart(2, '0');
const clamp01 = (v) => Math.max(0, Math.min(1, v));
const fc = (features) => ({type: 'FeatureCollection', features});
const feature = (geometry, properties = {}) => ({type: 'Feature', geometry, properties});
const escapeHtml = (s) =>
  String(s).replace(/[&<>"]/g, (c) => ({'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;'})[c]);
function mulberry32(seed) {
  return function () {
    seed |= 0;
    seed = (seed + 0x6d2b79f5) | 0;
    let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}
const rnd = mulberry32(20261023);

// 以 ORIGIN 为原点的局部平面坐标(米),用于面积、距离与建筑布置
const ORIGIN = [121.6, 31.2];
const M_PER_LNG = 111320 * Math.cos((ORIGIN[1] * Math.PI) / 180);
const M_PER_LAT = 110950;
const toLngLat = (x, y) => [ORIGIN[0] + x / M_PER_LNG, ORIGIN[1] + y / M_PER_LAT];
const toXY = (ll) => [(ll[0] - ORIGIN[0]) * M_PER_LNG, (ll[1] - ORIGIN[1]) * M_PER_LAT];
function pointInRing(x, y, ring) {
  let inside = false;
  for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) {
    const [ax, ay] = ring[i];
    const [bx, by] = ring[j];
    if (ay > y !== by > y && x < ((bx - ax) * (y - ay)) / (by - ay) + ax) {
      inside = !inside;
    }
  }
  return inside;
}
function ringArea(ring) {
  let sum = 0;
  ring.forEach((a, i) => {
    const b = ring[(i + 1) % ring.length];
    sum += a[0] * b[1] - b[0] * a[1];
  });
  return Math.abs(sum) / 2;
}

// ======================= 用地分类(GB 50137) =======================
const LAND = {
  R2: {name: '二类居住用地', group: 'R', color: '#f6dd5e'},
  B1: {name: '商业用地', group: 'B', color: '#ee6461'},
  B2: {name: '商务用地', group: 'B', color: '#c93c4f'},
  A2: {name: '文化设施用地', group: 'A', color: '#f6bdd8'},
  A31: {name: '高等院校用地', group: 'A', color: '#e48fbf'},
  A33: {name: '中小学用地', group: 'A', color: '#f19cc4'},
  A4: {name: '体育用地', group: 'A', color: '#f3a9c9'},
  A5: {name: '医疗卫生用地', group: 'A', color: '#d978b0'},
  M1: {name: '一类工业用地', group: 'M', color: '#bb8e66'},
  S4: {name: '交通场站用地', group: 'U', color: '#a3adb8'},
  G1: {name: '公园绿地', group: 'G', color: '#72c174'},
  X: {name: '待建用地', group: 'X', color: '#d6d9de'},
};
const GROUPS = [
  {key: 'R', name: '居住', color: '#f6dd5e'},
  {key: 'B', name: '商业商务', color: '#ee6461'},
  {key: 'A', name: '公共服务', color: '#f19cc4'},
  {key: 'M', name: '工业', color: '#bb8e66'},
  {key: 'U', name: '交通设施', color: '#a3adb8'},
  {key: 'G', name: '绿地', color: '#72c174'},
  {key: 'X', name: '待建', color: '#d6d9de'},
];
const SALEABLE = new Set(['R2', 'B1', 'B2', 'M1', 'X']);
const METRO_COLOR = {2: '#87d300', 13: '#e999c0', 14: '#626020', 16: '#77c8c7', 18: '#d6a461'};

// ======================= 车站与地块 =======================
const STATIONS = DATA.stations.map((s) => {
  const [x, y] = toXY(s.coord);
  return {name: s.name, coord: s.coord, x, y, hub: s.name === '张江高科'};
});
const HUB = STATIONS.find((s) => s.hub) || STATIONS[0];
function nearestStation(x, y) {
  let best = null;
  STATIONS.forEach((s) => {
    const d = Math.hypot(s.x - x, s.y - y);
    if (!best || d < best.d) {
      best = {station: s, d};
    }
  });
  return best;
}

// 编号:500 m 网格的列号-行号-序号
const PARCELS = [];
const PARCEL_BY_ID = new Map();
(function initParcels() {
  const seq = {};
  DATA.parcels.forEach((raw) => {
    const ring = raw.r.map(toXY);
    const cx = ring.reduce((s, q) => s + q[0], 0) / ring.length;
    const cy = ring.reduce((s, q) => s + q[1], 0) / ring.length;
    const zone = pad(Math.floor((cx + 4000) / 500)) + '-' + pad(Math.floor((cy + 4000) / 500));
    seq[zone] = (seq[zone] || 0) + 1;
    const near = nearestStation(cx, cy);
    const p = {
      id: zone + '-' + seq[zone],
      name: raw.n,
      land: raw.l,
      ring,
      cx,
      cy,
      area: ringArea(ring),
      station: near.station,
      stationD: near.d,
      hubD: Math.hypot(cx - HUB.x, cy - HUB.y),
      lngLats: raw.r.concat([raw.r[0]]),
      center: toLngLat(cx, cy),
    };
    p.feature = feature({type: 'Polygon', coordinates: [p.lngLats]}, {id: p.id});
    PARCELS.push(p);
    PARCEL_BY_ID.set(p.id, p);
  });
})();
const parcelOf = (props) => PARCEL_BY_ID.get(props.id);

// ======================= 规划指标(模拟):强度随离站距离衰减 =======================
const INDICATORS = {
  B: (near) => ({
    far: 3 + 3.6 * near + rnd() * 0.6,
    height: 60 + 120 * near,
    density: 0.4,
    green: 0.25,
  }),
  R2: (near, mid) => {
    const far = 1.6 + 1.1 * mid + rnd() * 0.35;
    return {far, height: 24 + far * 20, density: 0.22 + rnd() * 0.06, green: 0.35};
  },
  A: (near, mid, land) => ({
    far: 0.8 + rnd() * 0.7,
    height: land === 'A5' ? 60 : land === 'A31' ? 40 : 24,
    density: 0.3,
    green: 0.35,
  }),
  M1: () => ({far: 1.2 + rnd() * 0.8, height: 36, density: 0.45, green: 0.2}),
  S4: () => ({far: 0.5 + rnd() * 0.5, height: 18, density: 0.35, green: 0.3}),
  X: (near) => ({
    far: 2 + 2.5 * near + rnd() * 0.4,
    height: 40 + 80 * near,
    density: 0.35,
    green: 0.3,
  }),
  G1: () => ({far: 0, height: 0, density: 0.03, green: 0.8}),
};
PARCELS.forEach((p) => {
  const near = clamp01(1 - p.stationD / 700);
  const mid = clamp01(1 - p.stationD / 1500);
  const group = LAND[p.land].group;
  const fn = INDICATORS[p.land] || INDICATORS[group] || INDICATORS.G1;
  const v = fn(near * (p.station.hub ? 1 : 0.75), mid, p.land);
  p.far = Math.round(v.far * 10) / 10;
  p.height = Math.round(v.height / 5) * 5;
  p.density = v.density;
  p.green = v.green;
  p.floorArea = p.area * p.far;
});

// ======================= 土地出让(模拟):已建成地块由枢纽向外排在 2018–2026,待建地块排在其后 =======================
const YEARS = [2018, 2019, 2020, 2021, 2022, 2023, 2024, 2025, 2026, 2027, 2028];
const CUM_SHARE = [0.08, 0.17, 0.27, 0.37, 0.48, 0.59, 0.7, 0.8, 0.9, 0.96, 1];
const CURRENT_YEAR = 2026;
const BUYERS = [
  '张江集团',
  '浦东城投置业',
  '华启地产',
  '安居建设集团',
  '科创发展',
  '中科智造',
  '北辰实业',
  '新城产业基金',
];
(function initSupply() {
  const sale = PARCELS.filter((p) => SALEABLE.has(p.land));
  sale.forEach((p) => {
    p.score = p.hubD + rnd() * 1300 - (p.land === 'M1' ? 900 : 0) + (p.land === 'X' ? 1e6 : 0);
  });
  sale.sort((a, b) => a.score - b.score);
  sale.forEach((p, i) => {
    const share = (i + 0.5) / sale.length;
    p.saleYear = YEARS[CUM_SHARE.findIndex((c) => c >= share)];
    p.saleMonth = 3 + Math.floor(rnd() * 10);
    const yr = p.saleYear - YEARS[0];
    if (p.land === 'M1') {
      p.price = Math.round((380 + rnd() * 160 + yr * 12) / 10) * 10; // 工业用地按土地面积计价
      p.revenue = p.area * p.price;
    } else {
      const base =
        p.land === 'R2'
          ? 7000 + 5000 * clamp01(1 - p.stationD / 1600)
          : 2800 + 3200 * clamp01(1 - p.stationD / 900);
      p.price = Math.round((base + yr * 300 + rnd() * 800) / 100) * 100; // 楼面价
      p.revenue = p.floorArea * p.price;
    }
    p.premium = rnd() < 0.45 ? 0 : Math.round(rnd() * 280) / 10;
    p.buyer = BUYERS[Math.floor(rnd() * BUYERS.length)];
  });
})();
function supplyStatus(p, year) {
  if (!SALEABLE.has(p.land)) {
    return 'public';
  }
  if (p.saleYear <= year) {
    return 'sold';
  }
  return p.saleYear === year + 1 ? 'plan' : 'reserve';
}

// ======================= 建筑体量:按容积率与限高把建筑面积摊成若干栋 =======================
const MC_PER_METER = 1 / Math.cos((ORIGIN[1] * Math.PI) / 180);
const TOWER_SIDE = {
  R2: 22,
  B1: 46,
  B2: 42,
  M1: 70,
  A33: 50,
  A31: 54,
  A5: 48,
  A2: 56,
  S4: 40,
  X: 36,
};
const TOWERS = [];
PARCELS.forEach((p) => {
  if (!p.far) {
    return;
  }
  const xs = p.ring.map((q) => q[0]);
  const ys = p.ring.map((q) => q[1]);
  const inset = 12;
  const x0 = Math.min(...xs) + inset;
  const y0 = Math.min(...ys) + inset;
  const w = Math.max(...xs) - inset - x0;
  const h = Math.max(...ys) - inset - y0;
  if (w <= 0 || h <= 0) {
    return;
  }
  const side = TOWER_SIDE[p.land] || 30;
  const need = Math.max(
    1,
    Math.round(
      (p.floorArea / (side * side * Math.max(1, p.height / 3.2))) * (p.land === 'R2' ? 1.15 : 1),
    ),
  );
  const gap = side * (p.land === 'R2' ? 2.6 : 1.7);
  const nx = Math.max(1, Math.floor(w / gap));
  const ny = Math.max(1, Math.floor(h / gap));
  const r = side * 0.7;
  const cells = [];
  for (let i = 0; i < nx; i++) {
    for (let j = 0; j < ny; j++) {
      const gx = x0 + ((i + 0.5) * w) / nx;
      const gy = y0 + ((j + 0.5) * h) / ny;
      if (
        [
          [0, 0],
          [-r, -r],
          [r, -r],
          [r, r],
          [-r, r],
        ].every(([dx, dy]) => pointInRing(gx + dx, gy + dy, p.ring))
      ) {
        cells.push([gx, gy]);
      }
    }
  }
  if (!cells.length) {
    return;
  }
  // 靠近车站一侧优先布置
  cells.sort(
    (a, b) =>
      Math.hypot(a[0] - p.station.x, a[1] - p.station.y) -
      Math.hypot(b[0] - p.station.x, b[1] - p.station.y),
  );
  const n = Math.min(need, cells.length);
  const height = Math.min(p.height, (p.floorArea / (n * side * side)) * 3.2);
  const varied = p.land === 'R2' || p.land === 'B1' || p.land === 'B2';
  cells.slice(0, n).forEach(([x, y], k) => {
    TOWERS.push({
      parcel: p,
      coord: toLngLat(x, y),
      half: side / 2,
      height: Math.max(6, height * (k && varied ? 0.75 + 0.25 * rnd() : 1)),
    });
  });
});

// ======================= 填充图案:alpha 遮罩,颜色由 fillColor 决定 =======================
function patternUrl(draw) {
  const canvas = document.createElement('canvas');
  canvas.width = canvas.height = 32;
  const ctx = canvas.getContext('2d');
  ctx.fillStyle = ctx.strokeStyle = '#000';
  draw(ctx);
  return canvas.toDataURL('image/png');
}
const HATCH_URL = patternUrl((ctx) => {
  ctx.lineWidth = 3;
  [-32, 0, 32].forEach((o) => {
    ctx.beginPath();
    ctx.moveTo(o, 32);
    ctx.lineTo(o + 32, 0);
    ctx.stroke();
  });
});
const DOT_URL = patternUrl((ctx) => {
  [
    [8, 8],
    [24, 24],
  ].forEach(([x, y]) => {
    ctx.beginPath();
    ctx.arc(x, y, 2.6, 0, Math.PI * 2);
    ctx.fill();
  });
});

// ======================= 地图 =======================
const map = new BMap.Map('map', {enableAdaptiveMinZoom: false});
map.centerAndZoom(new BMap.Point(ORIGIN[0], ORIGIN[1]), 14);
map.enableScrollWheelZoom(true);
const REF = new BMap.Point(ORIGIN[0], ORIGIN[1]);
const SITE_BOUNDS = (() => {
  const lngs = DATA.mask.map((q) => q[0]);
  const lats = DATA.mask.map((q) => q[1]);
  return [
    new BMap.Point(Math.min(...lngs), Math.min(...lats)),
    new BMap.Point(Math.max(...lngs), Math.max(...lats)),
  ];
})();
const fitSite = (animate) =>
  map.setViewport(SITE_BOUNDS, {margins: [30, 300, 30, 340], enableAnimation: animate});
fitSite(false);

// 片区内以蒙层遮盖底图的 POI 与注记,路网、水系、路名改由图层绘制;所有图层置于 'poi' 阶段之上
const STAGE = 'poi';
const layerOptions = (zIndex, extra) =>
  Object.assign({referCenter: REF, zIndex, renderStage: STAGE}, extra);

const maskRing = DATA.mask.concat([DATA.mask[0]]);
const maskLayer = new BMap.PolygonLayer(layerOptions(1, {fillColor: '#f4f3ef', fillOpacity: 0.96}));
maskLayer.setData(feature({type: 'Polygon', coordinates: [maskRing]}));
const maskEdge = new BMap.PolylineLayer(
  layerOptions(30, {
    strokeColor: 'rgba(120, 132, 150, 0.55)',
    strokeWeight: 1.5,
    strokeStyle: 'dashed',
    dashArray: [10, 4, 2, 4],
  }),
);
maskEdge.setData(feature({type: 'LineString', coordinates: maskRing}));

const waterLayer = new BMap.PolygonLayer(layerOptions(2, {fillColor: '#b9d9ee', fillOpacity: 1}));
waterLayer.setData(
  fc(DATA.water.map((r) => feature({type: 'Polygon', coordinates: [r.concat([r[0]])]}))),
);
const riverLayer = new BMap.PolylineLayer(
  layerOptions(3, {strokeColor: '#b9d9ee', strokeWeight: (p) => (p.w ? 3 : 7)}),
);
riverLayer.setData(
  fc(DATA.rivers.map((r) => feature({type: 'LineString', coordinates: r.p}, {w: r.w}))),
);

const parcelLayer = new BMap.PolygonLayer(
  layerOptions(4, {
    fillColor: (props) => fillColorOf(parcelOf(props)),
    fillOpacity: (props) => fillOpacityOf(parcelOf(props)),
    strokeColor: '#ffffff',
    strokeWeight: 1,
    enablePicked: true,
  }),
);
const hatchLayer = new BMap.PolygonLayer(
  layerOptions(5, {
    fillColor: '#c43434',
    fillOpacity: 0.85,
    fillTextureUrl: HATCH_URL,
    fillTextureSize: 14,
    fillTextureAlphaOnly: true,
    visible: false,
  }),
);
const dotLayer = new BMap.PolygonLayer(
  layerOptions(6, {
    fillColor: '#46566a',
    fillOpacity: 0.55,
    fillTextureUrl: DOT_URL,
    fillTextureSize: 12,
    fillTextureAlphaOnly: true,
    visible: false,
  }),
);

// 道路分三级,每级一条描边线与一条填充线;线宽为屏幕像素,随级别缩放
const ROAD_STYLE = [
  {width: 5, fill: '#fbe2a0', edge: '#e2b864'},
  {width: 3.6, fill: '#ffffff', edge: '#cfd5dd'},
  {width: 1.8, fill: '#ffffff', edge: '#dde1e7'},
];
const roadScale = () => Math.max(0.7, Math.min(4, Math.pow(2, (map.getZoom() - 14) * 0.85)));
const roadLayers = [2, 1, 0].map((cls) => {
  const style = ROAD_STYLE[cls];
  const data = fc(DATA.roads[cls].map((r) => feature({type: 'LineString', coordinates: r})));
  const edge = new BMap.PolylineLayer(
    layerOptions(7 + (2 - cls) * 2, {
      strokeColor: style.edge,
      strokeWeight: (style.width + 1.6) * roadScale(),
    }),
  );
  const fill = new BMap.PolylineLayer(
    layerOptions(8 + (2 - cls) * 2, {
      strokeColor: style.fill,
      strokeWeight: style.width * roadScale(),
    }),
  );
  edge.setData(data);
  fill.setData(data);
  return {style, edge, fill};
});

function circle(x, y, r) {
  return Array.from({length: 65}, (_, a) =>
    toLngLat(x + r * Math.cos((a / 32) * Math.PI), y + r * Math.sin((a / 32) * Math.PI)),
  );
}
const todLayer = new BMap.PolylineLayer(
  layerOptions(14, {
    strokeColor: 'rgba(31, 111, 255, 0.85)',
    strokeWeight: 1.5,
    strokeStyle: 'dashed',
    dashArray: [6, 5],
    visible: false,
  }),
);
todLayer.setData(
  fc(
    STATIONS.flatMap((s) =>
      [500, 800].map((r) => feature({type: 'LineString', coordinates: circle(s.x, s.y, r)})),
    ),
  ),
);

const metroLayer = new BMap.PolylineLayer(
  layerOptions(15, {strokeColor: (p) => METRO_COLOR[p.line] || '#8a94a6', strokeWeight: 3.5}),
);
metroLayer.setData(
  fc(
    Object.keys(DATA.metro).map((k) =>
      feature({type: 'MultiLineString', coordinates: DATA.metro[k]}, {line: Number(k)}),
    ),
  ),
);

const selectionLayer = new BMap.PolylineLayer(
  layerOptions(16, {strokeColor: '#1f6fff', strokeWeight: 3.5}),
);
const towerLayer = new BMap.BarLayer(layerOptions(17, {unit: 'm', edgeCount: 4, visible: false}));

const stationLayer = new BMap.PointLayer(
  layerOptions(24, {
    size: (p) => (p.hub ? 13 : 10),
    fillColor: '#ffffff',
    strokeColor: '#1f2d3d',
    strokeWeight: 2.5,
  }),
);
stationLayer.setData(
  fc(STATIONS.map((s) => feature({type: 'Point', coordinates: s.coord}, {hub: s.hub}))),
);

// 所有注记放在同一个 TextLayer 内参与碰撞,按优先级排序:车站 > 干路 > 地块 > 支路
const LABEL_STYLE = {
  station: {size: 12, weight: 'bold', color: '#1f2d3d', stroke: '#ffffff'},
  road0: {size: 12, weight: 'bold', color: '#8a5a12', stroke: '#fbe2a0'},
  road1: {size: 12, weight: 'normal', color: '#5a6b80', stroke: '#ffffff'},
  road2: {size: 11, weight: 'normal', color: '#7b8794', stroke: '#ffffff'},
  parcel: {size: 11, weight: 'normal', color: '#2f3b4a', stroke: '#ffffff'},
};
const labelLayer = new BMap.TextLayer(
  layerOptions(25, {
    text: (p) => p.text,
    fontSize: (p) => LABEL_STYLE[p.kind].size,
    fontWeight: (p) => LABEL_STYLE[p.kind].weight,
    color: (p) => LABEL_STYLE[p.kind].color,
    strokeColor: (p) => LABEL_STYLE[p.kind].stroke,
    strokeWeight: 3,
    rotation: (p) => {
      if (p.angle == null) {
        return 0;
      }
      let a = p.angle + map.getHeading();
      while (a > 90) {
        a -= 180;
      }
      while (a < -90) {
        a += 180;
      }
      return a;
    },
    anchor: (p) => (p.kind === 'station' ? 'leftCenter' : 'center'),
    offset: (p) => (p.kind === 'station' ? [9, 0] : [0, 0]),
    margin: [6, 3],
  }),
);
const STATION_LABELS = STATIONS.map((s) =>
  feature({type: 'Point', coordinates: s.coord}, {kind: 'station', text: s.name}),
);
const ROAD_LABELS = DATA.roadLabels.map((l) =>
  feature({type: 'Point', coordinates: l.p}, {kind: 'road' + l.c, text: l.n, angle: l.a, cls: l.c}),
);

[
  maskLayer,
  waterLayer,
  riverLayer,
  parcelLayer,
  hatchLayer,
  dotLayer,
  todLayer,
  metroLayer,
  selectionLayer,
  towerLayer,
  maskEdge,
  stationLayer,
  labelLayer,
].forEach((layer) => map.addLayer(layer));
roadLayers.forEach((r) => {
  map.addLayer(r.edge);
  map.addLayer(r.fill);
});

// ======================= 专题样式 =======================
const state = {
  mode: 'use',
  year: CURRENT_YEAR,
  zScale: 2,
  selected: null,
  groups: new Set(GROUPS.map((g) => g.key)),
};

const FAR_STOPS = [
  [0.5, [255, 247, 220]],
  [1.5, [253, 214, 141]],
  [2.5, [251, 160, 72]],
  [4, [226, 92, 30]],
  [6, [140, 36, 12]],
];
function farColor(v) {
  if (v <= FAR_STOPS[0][0]) {
    return 'rgb(' + FAR_STOPS[0][1].join(',') + ')';
  }
  for (let i = 1; i < FAR_STOPS.length; i++) {
    const [v1, c1] = FAR_STOPS[i];
    if (v <= v1) {
      const [v0, c0] = FAR_STOPS[i - 1];
      const f = (v - v0) / (v1 - v0);
      return 'rgb(' + c0.map((c, k) => Math.round(c + (c1[k] - c) * f)).join(',') + ')';
    }
  }
  return 'rgb(' + FAR_STOPS[FAR_STOPS.length - 1][1].join(',') + ')';
}
const STATUS_OPACITY = {sold: 1, plan: 0.35, reserve: 0.18, public: 0.9};
function fillColorOf(p) {
  if (state.mode === 'intensity') {
    return p.far ? farColor(p.far) : LAND.G1.color;
  }
  if (state.mode === 'supply' && supplyStatus(p, state.year) === 'public') {
    return '#dfe3e8';
  }
  return LAND[p.land].color;
}
function fillOpacityOf(p) {
  if (state.mode === 'supply') {
    return STATUS_OPACITY[supplyStatus(p, state.year)];
  }
  return state.mode === 'intensity' && !p.far ? 0.5 : 0.78;
}
// 屏幕上容纳不下一行文字的地块不标注
function parcelLabel(p, zoom) {
  if (Math.sqrt(p.area) / (Math.pow(2, 18 - zoom) / 1.17) < 56) {
    return '';
  }
  if (state.mode === 'supply') {
    const status = supplyStatus(p, state.year);
    return status === 'sold'
      ? p.saleYear + ' 出让'
      : status === 'plan'
        ? '计划 ' + p.saleYear
        : status === 'reserve'
          ? '储备'
          : '';
  }
  if (state.mode === 'intensity') {
    return p.far && zoom >= 16 ? 'FAR ' + p.far.toFixed(1) : '';
  }
  return p.name || '';
}
const visibleParcels = () => PARCELS.filter((p) => state.groups.has(LAND[p.land].group));

// ======================= 渲染 =======================
// 14 级显示车站与干路名,15 级起显示地块名,16 级起显示支路名
function renderLabels() {
  const zoom = map.getZoom();
  const labels = STATION_LABELS.concat(ROAD_LABELS.filter((f) => f.properties.cls <= 1));
  if (zoom >= 15) {
    visibleParcels().forEach((p) => {
      const text = parcelLabel(p, zoom);
      if (text) {
        labels.push(feature({type: 'Point', coordinates: p.center}, {kind: 'parcel', text}));
      }
    });
  }
  if (zoom >= 16) {
    labels.push(...ROAD_LABELS.filter((f) => f.properties.cls === 2));
  }
  labelLayer.setData(fc(labels));
}
function renderTowers() {
  towerLayer.setData(
    fc(
      TOWERS.filter((t) => state.groups.has(LAND[t.parcel.land].group)).map((t) =>
        feature(
          {type: 'Point', coordinates: t.coord},
          {
            value: 1,
            size: t.half * MC_PER_METER,
            height: t.height * MC_PER_METER * state.zScale,
            color: farColor(t.parcel.far),
          },
        ),
      ),
    ),
  );
}
function renderSupplyPatterns() {
  const parcels = visibleParcels();
  hatchLayer.setData(
    fc(parcels.filter((p) => supplyStatus(p, state.year) === 'plan').map((p) => p.feature)),
  );
  dotLayer.setData(
    fc(parcels.filter((p) => supplyStatus(p, state.year) === 'reserve').map((p) => p.feature)),
  );
}
function renderData() {
  parcelLayer.setData(fc(visibleParcels().map((p) => p.feature)));
  renderTowers();
  renderSupplyPatterns();
  renderLabels();
}
// 样式回调依赖 state,重新设置同一回调即触发重算
function restyle() {
  const {fillColor, fillOpacity} = parcelLayer.getOptions();
  parcelLayer.setOptions({fillColor, fillOpacity});
  renderLabels();
}

function setMode(mode) {
  state.mode = mode;
  document
    .querySelectorAll('.tabs button')
    .forEach((b) => b.setAttribute('aria-pressed', String(b.dataset.mode === mode)));
  $('supplyPanel').hidden = mode !== 'supply';
  $('intensityPanel').hidden = mode !== 'intensity';
  hatchLayer.setVisible(mode === 'supply');
  dotLayer.setVisible(mode === 'supply');
  towerLayer.setVisible(mode === 'intensity');
  todLayer.setVisible(mode === 'intensity');
  if (mode === 'supply') {
    renderSupplyPatterns();
  }
  if (mode === 'intensity') {
    map.setTilt(58);
    map.setHeading(-28);
  } else if (map.getTilt() > 1) {
    map.setTilt(0);
    map.setHeading(0);
  }
  restyle();
  renderPanel();
  renderLegend();
  if (state.selected) {
    renderDetail(state.selected);
  }
}
function setYear(year) {
  state.year = year;
  $('year').value = year;
  $('yearLabel').textContent = year;
  renderSupplyPatterns();
  restyle();
  renderPanel();
  if (state.selected) {
    renderDetail(state.selected);
  }
}

// ======================= 面板 =======================
const hectare = (m2) => (m2 / 10000).toFixed(m2 < 100000 ? 2 : 1);
const yi = (yuan) => (yuan / 1e8).toFixed(yuan < 1e9 ? 2 : 1);
const kpi = (value, unit, label) =>
  '<div class="kpi"><b>' + value + '<em>' + unit + '</em></b><span>' + label + '</span></div>';

function buildGroupRows() {
  GROUPS.forEach((g) => {
    const button = document.createElement('button');
    button.type = 'button';
    button.className = 'grp';
    button.innerHTML =
      '<i class="sw"></i><span class="nm"></span><span class="bar"><i></i></span><span class="v"></span>';
    button.children[0].style.background = g.color;
    button.children[1].textContent = g.name;
    button.children[2].firstChild.style.background = g.color;
    button.addEventListener('click', () => {
      if (state.groups.has(g.key)) {
        state.groups.delete(g.key);
      } else {
        state.groups.add(g.key);
      }
      if (state.selected && !state.groups.has(LAND[state.selected.land].group)) {
        closeDetail();
      }
      renderData();
      renderPanel();
    });
    $('groups').appendChild(button);
  });
}

function renderPanel() {
  const parcels = visibleParcels();
  let area = 0;
  let floor = 0;
  let soldArea = 0;
  let soldCount = 0;
  let revenue = 0;
  let todFloor = 0;
  parcels.forEach((p) => {
    area += p.area;
    floor += p.floorArea;
    if (p.stationD < 800) {
      todFloor += p.floorArea;
    }
    if (supplyStatus(p, state.year) === 'sold') {
      soldArea += p.area;
      soldCount++;
      revenue += p.revenue;
    }
  });
  if (state.mode === 'supply') {
    $('kpis').innerHTML =
      kpi(soldCount, '宗', '已出让') +
      kpi(hectare(soldArea), 'ha', '出让面积') +
      kpi(yi(revenue), '亿', '出让金');
    drawYearChart();
  } else if (state.mode === 'intensity') {
    $('kpis').innerHTML =
      kpi((floor / 1e4).toFixed(0), '万㎡', '建筑面积') +
      kpi(area ? (floor / area).toFixed(2) : '0', '', '平均容积率') +
      kpi(floor ? Math.round((todFloor / floor) * 100) : 0, '%', '近站占比');
  } else {
    $('kpis').innerHTML =
      kpi(parcels.length, '块', '地块') +
      kpi(hectare(area), 'ha', '用地面积') +
      kpi((floor / 1e4).toFixed(0), '万㎡', '建筑面积');
  }

  const byGroup = {};
  let total = 0;
  PARCELS.forEach((p) => {
    const g = LAND[p.land].group;
    byGroup[g] = (byGroup[g] || 0) + p.area;
    total += p.area;
  });
  GROUPS.forEach((g, i) => {
    const row = $('groups').children[i];
    const share = (byGroup[g.key] || 0) / total;
    row.setAttribute('aria-pressed', String(state.groups.has(g.key)));
    row.children[2].firstChild.style.width = (share * 100).toFixed(1) + '%';
    row.children[3].textContent =
      hectare(byGroup[g.key] || 0) + ' ha · ' + (share * 100).toFixed(1) + '%';
  });
}

// 各年出让面积(按大类堆叠)与累计出让金
function drawYearChart() {
  const canvas = $('yearChart');
  const W = 278;
  const H = 104;
  const dpr = window.devicePixelRatio || 1;
  if (canvas.width !== W * dpr) {
    canvas.width = W * dpr;
    canvas.height = H * dpr;
  }
  const ctx = canvas.getContext('2d');
  ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  ctx.clearRect(0, 0, W, H);
  const cats = [
    ['R', '#f6dd5e'],
    ['B', '#ee6461'],
    ['M', '#bb8e66'],
    ['X', '#c4c9d0'],
  ];
  const perYear = YEARS.map(() => ({R: 0, B: 0, M: 0, X: 0, revenue: 0}));
  visibleParcels().forEach((p) => {
    if (!p.saleYear) {
      return;
    }
    const y = perYear[YEARS.indexOf(p.saleYear)];
    y[LAND[p.land].group] += p.area;
    y.revenue += p.revenue;
  });
  const maxArea = Math.max(...perYear.map((y) => y.R + y.B + y.M + y.X)) || 1;
  let sum = 0;
  const cumulative = perYear.map((y) => (sum += y.revenue));
  const maxRevenue = sum || 1;
  const top = 10;
  const base = H - 16;
  const bw = W / YEARS.length;
  perYear.forEach((y, k) => {
    let h0 = base;
    ctx.globalAlpha = YEARS[k] > state.year ? 0.28 : 1;
    cats.forEach(([key, color]) => {
      const h = (y[key] / maxArea) * (base - top - 8);
      ctx.fillStyle = color;
      ctx.fillRect(k * bw + 6, h0 - h, bw - 12, h);
      h0 -= h;
    });
    ctx.globalAlpha = 1;
    const current = YEARS[k] === state.year;
    ctx.fillStyle = current ? '#1f6fff' : '#7b8794';
    ctx.font = (current ? 'bold ' : '') + '10px sans-serif';
    ctx.textAlign = 'center';
    ctx.fillText(String(YEARS[k]).slice(2), k * bw + bw / 2, H - 4);
  });
  const yOf = (v) => base - (v / maxRevenue) * (base - top);
  ctx.strokeStyle = '#1f6fff';
  ctx.lineWidth = 1.5;
  ctx.beginPath();
  cumulative.forEach((v, k) =>
    k ? ctx.lineTo(k * bw + bw / 2, yOf(v)) : ctx.moveTo(k * bw + bw / 2, yOf(v)),
  );
  ctx.stroke();
  const cur = YEARS.indexOf(state.year);
  const cx = cur * bw + bw / 2;
  ctx.fillStyle = '#1f6fff';
  ctx.beginPath();
  ctx.arc(cx, yOf(cumulative[cur]), 3.5, 0, Math.PI * 2);
  ctx.fill();
  ctx.textAlign = cur > 5 ? 'right' : 'left';
  ctx.fillText(yi(cumulative[cur]) + ' 亿', cx + (cur > 5 ? -6 : 6), yOf(cumulative[cur]) - 6);
}

const swatch = (style, text) =>
  '<div class="li"><i class="sw" style="' + style + '"></i>' + text + '</div>';
function renderLegend() {
  let html;
  if (state.mode === 'supply') {
    html =
      '<h2>' +
      state.year +
      ' 年供地状态</h2>' +
      swatch('background:#f6dd5e', '已出让') +
      swatch(
        'background:repeating-linear-gradient(135deg,#c43434 0 2px,rgba(246,221,94,.35) 2px 6px)',
        '下一年计划出让',
      ) +
      swatch(
        'background:radial-gradient(circle,#46566a 1.4px,rgba(246,221,94,.18) 1.6px) 0 0/6px 6px',
        '储备',
      ) +
      swatch('background:#dfe3e8', '公益性用地');
  } else if (state.mode === 'intensity') {
    html =
      '<h2>容积率</h2><div class="ramp" style="background:linear-gradient(90deg,' +
      FAR_STOPS.map((s) => 'rgb(' + s[1].join(',') + ')').join(',') +
      ')"></div>' +
      '<div class="ticks">' +
      FAR_STOPS.map((s) => '<span>' + s[0] + '</span>').join('') +
      '</div>' +
      swatch('border:1.5px dashed #1f6fff;background:none', '站点 500 / 800 m');
  } else {
    const used = new Set(PARCELS.map((p) => p.land));
    html =
      '<h2>用地性质</h2><div class="items">' +
      Object.keys(LAND)
        .filter((k) => used.has(k))
        .map((k) =>
          swatch('background:' + LAND[k].color, k + ' ' + LAND[k].name.replace('用地', '')),
        )
        .join('') +
      '</div>';
  }
  html +=
    '<div class="lines">' +
    Object.keys(DATA.metro)
      .map(
        (k) =>
          '<span><i style="border-color:' +
          (METRO_COLOR[k] || '#8a94a6') +
          '"></i>' +
          k +
          ' 号线</span>',
      )
      .join('') +
    '</div>';
  $('legend').innerHTML = html;
}

// ======================= 地块详情 =======================
const STATUS_TAG = {
  sold: ['已出让', '#e9f6ec', '#2d8a4e'],
  plan: ['计划出让', '#fdecec', '#c43434'],
  reserve: ['储备', '#eef1f5', '#46566a'],
  public: ['划拨', '#eef1f5', '#7b8794'],
};
function renderDetail(p) {
  const land = LAND[p.land];
  const status = supplyStatus(p, state.year);
  const [tagText, tagBg, tagColor] = STATUS_TAG[status];
  let supply;
  if (status === 'sold') {
    supply =
      p.saleYear +
      '-' +
      pad(p.saleMonth) +
      ' 出让 · ' +
      escapeHtml(p.buyer) +
      '<br>' +
      (p.land === 'M1' ? '地面价 ' : '楼面价 ') +
      p.price.toLocaleString() +
      ' 元/㎡ · 溢价 ' +
      p.premium +
      '%' +
      '<br>成交价 ' +
      yi(p.revenue) +
      ' 亿元';
  } else if (status === 'public') {
    supply = '划拨供地';
  } else {
    supply =
      '计划 ' +
      p.saleYear +
      ' 年供地 · 参考楼面价 ' +
      Math.round(p.price * 0.92).toLocaleString() +
      ' 元/㎡';
  }
  const item = (label, value, unit) =>
    '<dt>' + label + '</dt><dd>' + value + (unit ? ' <small>' + unit + '</small>' : '') + '</dd>';
  $('detail').innerHTML =
    '<div class="head"><span class="code" style="background:' +
    land.color +
    '">' +
    p.land +
    '</span>' +
    '<b>' +
    escapeHtml(p.name || p.id) +
    '</b><button class="close" type="button" aria-label="关闭">×</button></div>' +
    '<div class="sub">' +
    p.id +
    ' · ' +
    land.name +
    '<span class="tag" style="background:' +
    tagBg +
    ';color:' +
    tagColor +
    '">' +
    tagText +
    '</span></div>' +
    '<dl>' +
    item('用地面积', hectare(p.area), 'ha') +
    item('容积率', p.far ? '≤ ' + p.far.toFixed(1) : '—') +
    item('建筑限高', p.height || '—', p.height ? 'm' : '') +
    item('建筑密度', '≤ ' + Math.round(p.density * 100), '%') +
    item('绿地率', '≥ ' + Math.round(p.green * 100), '%') +
    item('距' + escapeHtml(p.station.name) + '站', Math.round(p.stationD), 'm') +
    '</dl><div class="supply">' +
    supply +
    '</div>';
  $('detail').style.display = 'block';
  $('detail').querySelector('.close').addEventListener('click', closeDetail);
  selectionLayer.setData(feature({type: 'LineString', coordinates: p.lngLats}));
}
function selectParcel(p, locate) {
  state.selected = p;
  renderDetail(p);
  if (locate) {
    map.panTo(new BMap.Point(p.center[0], p.center[1]));
    if (map.getZoom() < 15.5) {
      map.setZoom(16);
    }
  }
}
function closeDetail() {
  state.selected = null;
  $('detail').style.display = 'none';
  selectionLayer.clearData();
}

// ======================= 交互 =======================
const tooltip = $('tooltip');
parcelLayer.addEventListener('click', (e) => selectParcel(parcelOf(e.value.properties), false));
parcelLayer.addEventListener('mousemove', (e) => {
  const p = parcelOf(e.value.properties);
  tooltip.innerHTML =
    '<b>' +
    escapeHtml(p.name || p.id) +
    '</b> · ' +
    LAND[p.land].name +
    '<br>' +
    hectare(p.area) +
    ' ha' +
    (p.far ? ' · 容积率 ' + p.far.toFixed(1) : '');
  tooltip.style.left = e.pixel.x + 14 + 'px';
  tooltip.style.top = e.pixel.y + 14 + 'px';
  tooltip.style.display = 'block';
});
parcelLayer.addEventListener('mouseout', () => {
  tooltip.style.display = 'none';
});
map.addEventListener('movestart', () => {
  tooltip.style.display = 'none';
});
document.addEventListener('keydown', (e) => {
  if (e.key === 'Escape') {
    closeDetail();
  }
});

// 缩放跨越注记分级时刷新注记;zoom_changed 时 getZoom 尚未更新,延后一个任务读取
const zoomLevelOf = () => {
  const z = map.getZoom();
  return z >= 16 ? 2 : z >= 15 ? 1 : 0;
};
let labelLevel = zoomLevelOf();
let lastRoadScale = roadScale();
map.addEventListener('zoom_changed', () =>
  setTimeout(() => {
    const level = zoomLevelOf();
    if (level !== labelLevel) {
      labelLevel = level;
      renderLabels();
    }
  }, 0),
);
map.addEventListener('zoomend', () => {
  const k = roadScale();
  if (Math.abs(k - lastRoadScale) < 0.05) {
    return;
  }
  lastRoadScale = k;
  roadLayers.forEach(({style, edge, fill}) => {
    edge.setOptions({strokeWeight: (style.width + 1.6) * k});
    fill.setOptions({strokeWeight: style.width * k});
  });
});
map.addEventListener('heading_changed', () =>
  labelLayer.setOptions({rotation: labelLayer.getOptions().rotation}),
);

document
  .querySelectorAll('.tabs button')
  .forEach((b) => b.addEventListener('click', () => setMode(b.dataset.mode)));

const yearInput = $('year');
yearInput.min = YEARS[0];
yearInput.max = YEARS[YEARS.length - 1];
yearInput.addEventListener('input', () => setYear(Number(yearInput.value)));
let yearTimer = null;
$('yearPlay').addEventListener('click', (e) => {
  const button = e.currentTarget;
  if (yearTimer) {
    clearInterval(yearTimer);
    yearTimer = null;
    button.textContent = '回放';
    return;
  }
  button.textContent = '暂停';
  setYear(YEARS[0]);
  yearTimer = setInterval(() => {
    if (state.year >= YEARS[YEARS.length - 1]) {
      clearInterval(yearTimer);
      yearTimer = null;
      button.textContent = '回放';
      return;
    }
    setYear(state.year + 1);
  }, 1000);
});
$('zScale').addEventListener('change', (e) => {
  state.zScale = Number(e.target.value);
  renderTowers();
});
$('viewReset').addEventListener('click', () => {
  map.setTilt(0);
  map.setHeading(0);
  fitSite(true);
});

PARCELS.forEach((p) => {
  const option = document.createElement('option');
  option.value = p.name || p.id;
  option.label = p.id;
  $('parcelIds').appendChild(option);
});
function search() {
  const input = $('search');
  const q = input.value.trim();
  const p =
    q &&
    (PARCEL_BY_ID.get(q) ||
      PARCELS.find((x) => x.name === q) ||
      PARCELS.find((x) => x.id.startsWith(q) || (x.name && x.name.includes(q))));
  if (!p) {
    input.setCustomValidity('未找到地块');
    input.reportValidity();
    return;
  }
  input.setCustomValidity('');
  const group = LAND[p.land].group;
  if (!state.groups.has(group)) {
    state.groups.add(group);
    renderData();
    renderPanel();
  }
  selectParcel(p, true);
}
$('searchBtn').addEventListener('click', search);
$('search').addEventListener('keydown', (e) => {
  if (e.key === 'Enter') {
    search();
  }
});
$('search').addEventListener('input', (e) => e.target.setCustomValidity(''));

buildGroupRows();
setYear(CURRENT_YEAR);
renderData();
renderPanel();
renderLegend();
预览