Daz*_*zle 0 leaflet vue.js vuejs2
我正在尝试创建一个 Leaflet 地图作为 Vue 组件,但我有一些困难的开始。我通过 npm 安装了 Leaflet
我哪里错了?console.log(Leaflet) 正在返回一个 Leaflet 对象,但我无法让地图展开和渲染。
一些方向将不胜感激
<template>
<div id="map"></div>
</template>
<script>
// import leaflet here?
import Leaflet from 'leaflet';
export default {
components: {
Leaflet
},
created() {
console.log(this);
console.log(Leaflet);
},
ready() {
this.map = L.map('map').setView([51.959, -8.623], 14);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(this.map);
}
}
</script>
<style>
#map {
height: 100%;
width: 100%;
margin-top: -24px;
}
/* default legend, layer styling from leaflet template */
.info {
padding: 6px 8px;
font: 14px/16px Arial, Helvetica, sans-serif;
background: white;
background: rgba(255,255,255,0.8);
box-shadow: 0 0 15px rgba(0,0,0,0.2);
border-radius: 5px;
}
.info h4 {
margin: 0 0 5px;
color: #777;
}
.legend {
text-align: left;
line-height: 18px;
color: #555;
}
.legend i {
width: 18px;
height: 18px;
float: left;
margin-right: 8px;
opacity: 0.7;
}
</style>
Run Code Online (Sandbox Code Playgroud)
您的代码中有几个问题:
readyVue 中没有生命周期钩子。使用mounted().map数据资产并没有在Vue的组件上宣布。Leaflet from 'leaflet',但是将 Leaflet 对象声明为 可能对您自己或其他人更一致L from 'leaflet'。您也可以使用: import { Map } from 'leaflet',但必须适当地初始化您的地图:this.map = new Map("mapContainer")remove()Leaflet Map Class 上的方法,适当地防止潜在的内存泄漏和/或清理。VuebeforeDestroy生命周期钩子是一个很好的地方。另外,不要忘记导入 Leaflet CSS,例如:
import "leaflet/dist/leaflet.css";
<template>
<div id="mapContainer"></div>
</template>
<script>
import "leaflet/dist/leaflet.css";
import L from "leaflet";
export default {
name: "LeafletMap",
data() {
return {
map: null
};
},
mounted() {
this.map = L.map("mapContainer").setView([51.959, -8.623], 12);
L.tileLayer("http://{s}.tile.osm.org/{z}/{x}/{y}.png", {
attribution:
'© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(this.map);
},
beforeDestroy() {
if (this.map) {
this.map.remove();
}
}
};
</script>
<style scoped>
#mapContainer {
width: 100vw;
height: 100vh;
}
</style>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4597 次 |
| 最近记录: |