今天要來用 GeoJSON 產生地圖,並且用選單觸摸時顯示對應的區塊。
功能說明:
import { cityData } from "./us-states.js";
let geoJSON = [];
let map = {};
onMounted(() => {
map = L.map(mapContainer.value).setView([53.8, -110], 4);
geoJSON = L.geoJSON(cityData, {
style: {
color: "#e91e63",
weight: 2,
fillColor: "#ffeb3b",
fillOpacity: 0.15,
},
});
geoJSON.addTo(map);
}
初始化 GeoJson
<Menu :currentCityId="currentCityId" :cityData="cityData" />
import { cityData } from "./us-states.js";
const currentCityId = ref("");
初始化選單
menu 元件
<li @mouseover="$emit('setAreaHighlight', city)"
@mouseout="$emit('resetAreaHighlight', city)"></li>
父層
<Menu @setAreaHighlight="setAreaHighlight"
@resetAreaHighlight="resetAreaHighlight" />
setStyle() 設定摸到區塊時的顏色
const setAreaHighlight = (city) => {
getFilterArea(city)[0].setStyle({
weight: 4,
fillOpacity: 0.7,
});
};
const resetAreaHighlight = (city) => {
geoJSON.resetStyle(getFilterArea(city)[0]);
};
const onEachFeature = (feature, layer) => {
layer.addEventListener("mouseover", (e) => {
e.target.setStyle({
weight: 4,
fillOpacity: 0.7,
});
currentCityId.value = e.target.feature.id;
});
layer.addEventListener("mouseout", (e) => {
geoJSON.resetStyle(e.target);
currentCityId.value = "";
});
};
onMounted(() => {
L.geoJSON(cityData, {
onEachFeature: onEachFeature,
});
})
範例完成
範例連結
https://github.com/XuanCbbLin/Vue3-leaflet/tree/master/src/components/LinkedView