【发布时间】:2020-03-27 11:09:05
【问题描述】:
我正在尝试使用 Leaflet 和 Vue 组件创建地图。出于某种原因,“中心:”属性不接受我的纬度和经度数组坐标?当我在模板 html {{ latlng }} 中使用它时,我得到一个具有正确坐标的数组。任何帮助将不胜感激。
<template>
<div id="mapContainer">{{ latlng }}</div>
</template>
<script>
import "leaflet/dist/leaflet.css";
import L from "leaflet";
import axios from 'axios';
export default {
name: "Map",
data() {
return {
map: null,
latlng: []
};
},
methods: {
get_lat_lng: function(){
axios.get('http://127.0.0.1:5000/api/get_latitude')
.then(res => this.latlng.push(res.data))
axios.get('http://127.0.0.1:5000/api/get_longitude')
.then(res => this.latlng.push(res.data))
}
},
created: function(){
this.get_lat_lng()
},
mounted() {
this.map = L.map("mapContainer", {
center: this.latlng,
zoom: 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: 50vw;
height: 50vh;
}
</style>
【问题讨论】:
-
可能是在 axios 异步调用完成之前调用了mounted() 方法。你需要稍微改变你的逻辑,所以地图不是在挂载时创建,而是在 axios 完成时创建。
-
我尝试将 axios 调用直接放在 created() 中。根据生命周期图,created 在mounted 之前运行。不太确定这里发生了什么。
-
调用顺序大概就是这个1.created(), 2.mounted(), 3.axios.then()。
-
所以需要在axios.then()调用中初始化地图
标签: javascript vue.js leaflet