在Astro中使用leafletjs渲染Directus Map地图字段

在Astro中使用leafletjs渲染Directus Map地图字段

Directus的Map字段在api中会生成出标准的GeoJSON数据格式,在使用的时候也非常简单,leafletjs官方网站就提供了对GeoJSON格式数据的使用方法

这里需要注意的是Astro使用define<script>区域中传入变量,在这里有很详细的说明,所以在使用define之前拿到地图坐标数据之后无法传入到地图中,这个问题困扰了我很久。

最后上实现代码吧

---
const response = await fetch('http://127.0.0.1:8055/items/routes');
const routes = await response.json();
---
<!DOCTYPE html>
<html lang="en">
<head>
	<base target="_top">
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Quick Start - Leaflet</title>
  <link rel="stylesheet" href="/leaflet/leaflet.css" />
  <script src="/leaflet/leaflet.js" is:inline></script>
  <style>#map { height: 680px; }</style>
</head>
<body>
  <div id="map"></div>

  <script define:vars={{ routes: routes }}>

  var map = L.map('map').setView([51.505, -0.09], 13);

  L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
      attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
  }).addTo(map);

  L.marker([51.5, -0.09]).addTo(map)
      .bindPopup('A pretty CSS3 popup.<br> Easily customizable.')
      .openPopup();
  

function onEachFeature(feature, layer) {
    // does this feature have a property named popupContent?
    if (feature.properties && feature.properties.popupContent) {
        layer.bindPopup(feature.properties.popupContent);
    }
}

var geojsonFeature = [];

routes.data.map((r) => (
  geojsonFeature.push({
    "type": "Feature",
    "properties": {
        "name": "Coors Field",
        "amenity": "Baseball Stadium",
        "popupContent": r.name
    },
    "geometry": r.route
    })
));

L.geoJSON(geojsonFeature, {
    onEachFeature: onEachFeature
}).addTo(map);

  </script>
</body>
</html>

Post Comment