<template> <div class="home"> <div id="container" class="allmap"></div> </div> </template> <script> // bmpgl.js export function BMPGL(ak) { return new Promise(function(resolve, reject) { window.init = function() { resolve(BMapGL) } const script = document.createElement('script') script.type = 'text/javascript' script.src = `http://api.map.baidu.com/api?v=1.0&type=webgl&ak=${ak}&callback=init` script.onerror = reject document.head.appendChild(script) }) } import { BMPGL } from "@/bmpgl.js" export default { name: "BaiDuMap", data() { return { ak: "UY607Rv3yQPpAXIFRHWHuyk2CV4Hqgj0", // 百度的地图密钥 myMap: null }; }, mounted() { this.initMap() }, methods: { initMap() { BMPGL(this.ak).then((BMapGL) => { let map = new BMapGL.Map("container"); let point = new BMapGL.Point(121.530027,38.867479) map.centerAndZoom(point, 19) var marker = new BMapGL.Marker(point); map.addOverlay(marker); map.enableScrollWheelZoom(true) var scaleCtrl = new BMapGL.ScaleControl(); map.addControl(scaleCtrl); var zoomCtrl = new BMapGL.ZoomControl(); map.addControl(zoomCtrl); }) .catch((err)=>{ console.log(err) }) }, } }; </script> <style> .allmap { width: 100%; height: 300px; position: relative; z-index: 1; } </style> 使用vue3 更改代码使其在一个.vue文件呈现
时间: 2024-02-14 21:18:58 浏览: 133
你可以将上述代码保存为一个名为BaiDuMap.vue的文件,然后在你的Vue应用程序中引入该组件。下面是一个示例:
```
<template>
<div class="BaiDuMap">
<div class="map-container">
<div id="container" class="allmap"></div>
</div>
</div>
</template>
<script>
import { BMPGL } from "@/bmpgl.js";
export default {
name: "BaiDuMap",
data() {
return {
ak: "UY607Rv3yQPpAXIFRHWHuyk2CV4Hqgj0",
myMap: null
};
},
mounted() {
this.initMap();
},
methods: {
initMap() {
BMPGL(this.ak)
.then((BMapGL) => {
let map = new BMapGL.Map("container");
let point = new BMapGL.Point(121.530027, 38.867479);
map.centerAndZoom(point, 19);
var marker = new BMapGL.Marker(point);
map.addOverlay(marker);
map.enableScrollWheelZoom(true);
var scaleCtrl = new BMapGL.ScaleControl();
map.addControl(scaleCtrl);
var zoomCtrl = new BMapGL.ZoomControl();
map.addControl(zoomCtrl);
})
.catch((err) => {
console.log(err);
});
}
}
};
</script>
<style scoped>
.map-container {
width: 100%;
height: 300px;
position: relative;
z-index: 1;
}
</style>
```
在你的Vue应用程序的模板中,你可以像这样使用该组件:
```
<template>
<div>
<BaiDuMap />
</div>
</template>
<script>
import BaiDuMap from "@/components/BaiDuMap.vue";
export default {
components: {
BaiDuMap
}
};
</script>
```
这将在你的Vue应用程序中呈现一个名为BaiDuMap的组件,它将显示一个百度地图,并显示一个位于(121.530027, 38.867479)的标记。
阅读全文