Skip to content

GeoJSON

上次更新 2025年8月20日星期三 3:16:20 字数 0 字 时长 0 分钟

示例

TIP

以下实例演示了如何在 Leaflet 中使用 GeoJSON 数据来展示地理信息。 geojson leaflet 教程

新标签页预览

代码实现


vue
<template>
  <div id="map" class="w-full h-96"></div>
</template>

<script setup>
import L from "leaflet";
import "leaflet/dist/leaflet.css";
import { onMounted, ref } from "vue";

const map = ref(null);

onMounted(() => {
  map.value = L.map("map", {
    center: [39.094899, 117.33083], // 天津
    zoom: 4, // 缩放比列
    zoomControl: true,
    attributionControl: false, // 不展示版权信息
  });

  L.tileLayer(
    "http://t0.tianditu.gov.cn/vec_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=d32c6748c80f81a44acd8633cea41dfd"
  ).addTo(map.value);

  // GeoJSON 数据
  let geojsonFeature = {
    type: "Feature",
    properties: {
      name: "Point",
    },
    geometry: {
      type: "Point",
      coordinates: [117.33083, 39.094899],
    },
  };

  // 添加 GeoJSON 数据
  L.geoJSON(geojsonFeature, {
    style: {
      color: "red",
      weight: 100, // 增加线条宽度
      fillColor: "red",
      fillOpacity: 0.5, // 增加填充透明度
    },
  }).addTo(map.value);

  // 添加 FeatureCollections 数据
  const featureCollections = {
    type: "FeatureCollections",
    features: [
      {
        type: "Feature",
        properties: { name: "polygon1" },
        geometry: {
          type: "Polygon",
          coordinates: [
            [
              [117.32248306274415, 39.107827920205374],
              [117.31578826904298, 39.09291571258751],
              [117.33707427978517, 39.083593981163304],
              [117.35578536987306, 39.09584514515822],
              [117.34857559204103, 39.11022423079904],
              [117.32248306274415, 39.107827920205374],
            ],
          ],
        },
      },
    ],
  };

  const layer2 = L.geoJSON(featureCollections, {
    style: {
      color: "blue",
      weight: 2, // 增加线条宽度
      fillColor: "blue",
      fillOpacity: 0.1, // 增加填充透明度
    },
  }).addTo(map.value);

  // 定位到多边形区域
  map.value.fitBounds(layer2.getBounds());
});
</script>
关注公众号