前面幾天講解了 Leaflet.js 一些基本的設定,之後要將前面介紹的內容做一些小
範例。
<div class="w-full" ref="mapContent"></div>
<script setup>
let map = {};
const mapContent = ref(null);
onMounted(() => {
map = L.map(mapContent.value).setView([23.695, 121.102], 8);
L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
maxZoom: 19,
attribution: '© <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>',
}).addTo(map);
}
</script>
currentCoordinate : 紀錄亂數座標的選單
getRandom : 亂數函式
<ul class="w-[500px] h-[900px] overflow-y-scroll">
<li
class="px-2 py-3 text-center cursor-pointer hover:bg-gray-200"
v-for="coordinate in coordinateMenu"
:key="coordinate"
>
{{ `${coordinate.latitude} , ${coordinate.longtitude}` }}
</li>
</ul>
const currentCoordinate = ref(null);
const getRandom = (min, max) => {
return Math.random() * (max - min) + min;
};
for (let i = 0; i < 20; i++) {
coordinateMenu[i] = { latitude: getRandom(22, 25), longtitude: getRandom(120, 122) };
}
選單
markers : 20筆 icon 的資料
const markers = [];
onMounted(() => {
coordinateMenu.forEach((coordinate, index) => {
markers[index] = L.marker([coordinate.latitude, coordinate.longtitude]);
markers[index].bindPopup(`${coordinate.latitude} , ${coordinate.longtitude}`).addTo(map);
});
});
});
地圖上的座標
<ul class="w-[500px] h-[900px] overflow-y-scroll">
<li v-for="coordinate in coordinateMenu"
:key="coordinate"
:class="{ 'bg-gray-200': currentCoordinate === coordinate }"
@click="moveMarker(coordinate)">
</li>
</ul>
currentCoordinate : 當點擊地圖上的 icon 或選單上的座標紀錄目前座標,修改選單樣式
moveMarker : 移動到點擊的 icon
const currentCoordinate = ref(null);
const moveMarker = (coordinate) => {
currentCoordinate.value = coordinate;
const filterMarker = markers.filter((marker) => {
return marker._latlng.lat === coordinate.latitude && marker._latlng.lng === coordinate.longtitude ;
});
filterMarker[0].openPopup();
map.flyTo([coordinate.latitude, coordinate.longtitude], 9);
};
onMounted(() => {
coordinateMenu.forEach((coordinate, index) => {
markers[index].addEventListener("click", (e) => {
const filterMarker = coordinateMenu.filter((coordinate) => {
return e.latlng.lat === coordinate.latitude && e.latlng.lng === coordinate.longtitude;
});
currentCoordinate.value = filterMarker[0];
map.flyTo([e.latlng.lat, e.latlng.lng], 9);
});
});
});
完成範例
GitHub :
https://github.com/XuanCbbLin/Vue3-leaflet/blob/master/src/components/RandomIcons/RandomIcons.vue