起步


开发

  • 引入百度地图 JSSDK
  • 创建地图容器
  • 通过 centerAndZoom 设置地理位置和缩放比例尺
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script
type="text/javascript"
src="https://api.map.baidu.com/api?v=1.0&type=webgl&ak=aafKSTDs4p0zXAkRHGc5GEchvukRlD2I"
></script>
<style>
.map-wraper {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
}
</style>
</head>
<body>
<div id="mapWraper" class="map-wraper"></div>
<script>
// 创建百度地图地图容器
const mapWraper = document.querySelector("#mapWraper");
// 创建百度地图实例
const map = new BMapGL.Map(mapWraper);
// 创建定位坐标轴(经、纬度)
const point = new BMapGL.Point(116.404, 39.915);
// 设置中心点和缩放比例尺
map.centerAndZoom(point, 15);
</script>
</body>
</html>

Vue 项目中使用

简单示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width,initial-scale=1.0,user-scalable=no" />
<link rel="icon" href="<%= BASE_URL %>favicon.ico" />
<title><%= htmlWebpackPlugin.options.title %></title>
<script
type="text/javascript"
src="https://api.map.baidu.com/api?v=1.0&&type=webgl&ak=hwNUUNPWZxCFfxrnG0PitheUGLUVSNNL"
></script>
</head>
<body>
<noscript>
<strong
>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work
properly without JavaScript enabled. Please enable it to
continue.</strong
>
</noscript>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>
  • 创建 BMap 组件

如果项目中使用了 eslint 等相关插件,需要使用 /_ eslint-disable no-undef _/ 关闭错误提示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<template>
<div class="map-wraper" ref="mapWraper">this is bmap</div>
</template>

<script>
/* eslint-disable no-undef */
import { defineComponent, onMounted, ref } from "vue";
export default defineComponent({
name: "BMap",
setup() {
let mapWraper = ref(null);
let map = null;
let init = () => {
// 初始化百度地图
map = new BMapGL.Map(mapWraper.value);
// 设置中心点和缩放比例尺
map.centerAndZoom(new BMapGL.Point(116.404, 39.915), 11);
};
onMounted(() => {
init();
});
return {
map,
mapWraper,
};
},
});
</script>

<style>
/* 一定要设置地图容器的宽高,本人喜欢用定位解决*/
.map-wraper {
position: absolute;
top: 44px;
bottom: 44px;
width: 100%;
}
</style>
  • 页面调用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<template>
<div class="content-wraper">
this is map page
<BMap></BMap>
</div>
</template>

<script>
import BMap from "@/components/map";
import { defineComponent } from "vue";
export default defineComponent({
name: "Map",
components: {
BMap,
},
});
</script>

<style>

.content-wraper {
width: 100%;
height: 100%;
position: relative;
}
</style>