请你扮演一个前端开发工程师,用vue写一个百度地图加载geojson数据的完整案例
时间: 2024-06-10 16:04:16 浏览: 15
好的,我可以扮演一个前端开发工程师,以下是用vue实现百度地图加载geojson数据的完整案例:
首先,在项目中安装百度地图 JavaScript API 和 vue-baidu-map 库:
```bash
npm i vue-baidu-map baidu-map --save
```
然后,在项目中创建一个地图组件 BaiduMap.vue,代码如下:
```vue
<template>
<div class="map-container">
<baidu-map
:center="center"
:zoom="zoom"
:style="{width: '100%', height: '100%'}">
<div v-for="(feature,index) in features" :key="index">
<baidu-overlay
v-if="feature.type === 'Point'"
:position="feature.geometry.coordinates"
:offset="[0, 0]"
:zIndex="10"
:content="feature.properties.name"
style="font-size: 14px; color: #fff; background-color: rgba(0, 122, 208, 0.8); cursor: pointer; padding: 5px; border-radius: 5px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.3)">
</baidu-overlay>
<baidu-polygon
v-else-if="feature.type === 'Polygon'"
:strokeColor="#f00"
:strokeWeight="2"
:fillColor="feature.properties.color"
:paths="[feature.geometry.coordinates[0]]">
<div :slot="index">
<p>{{feature.properties.name}}</p>
</div>
</baidu-polygon>
</div>
</baidu-map>
</div>
</template>
<script>
import {BaiduMap, BaiduOverlay, BaiduPolygon} from 'vue-baidu-map'
export default {
components: {
BaiduMap,
BaiduOverlay,
BaiduPolygon
},
data() {
return {
center: [116.404, 39.915],
zoom: 11,
features: []
}
},
mounted() {
this.loadGeojson()
},
methods: {
loadGeojson() {
const self = this
const xhr = new XMLHttpRequest()
xhr.open('GET', './data.geojson', true)
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
const data = JSON.parse(xhr.responseText)
self.features = data.features
}
}
xhr.send()
}
}
}
</script>
<style>
.map-container {
width: 100%;
height: 100%;
}
</style>
```
上述代码中,我们引入了 vue-baidu-map 库和百度地图 JavaScript API,创建了一个地图容器,并在其中添加了 baidu-map 组件。
在 mounted 钩子函数中,我们使用原生 JavaScript 加载了本地的 GeoJSON 数据,并将其中的 features 数组设置为组件的 data 中的 features 数组,以供后续渲染地图使用。
在 baidu-map 组件内部,我们遍历了 features 数组,并对每个 feature 进行分类处理。如果 feature 是 Point 类型,我们就使用 baidu-overlay 组件实现了一个自定义信息窗口。如果 feature 是 Polygon 类型,我们就使用 baidu-polygon 组件实现了一个自定义多边形,并使用插槽中的内容呈现了多边形名称。
最后,我们可以直接在父组件中使用 BaiduMap 组件,并将其插入到页面中的任意位置即可。同时,我们可以通过修改 GeoJSON 中 features 数组的数据来动态地更新地图中的内容。
希望这个案例可以帮助到您,若您有其他问题,请继续提问。