百度地图 - 基础学习(1): 地图开发环境搭建

Vue项目接入百度地图,这次学习用的是原生API。javascript

1、引入百度地图JS

在 index.html 内添加script标签,引入百度地图api地址:html

<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=百度地图秘钥(ak)"></script>

2、API调用,地图初始化

一、容器节点准备

完成百度地图引入之后,就能够进行地图api调用了。但,在地图初始化api调用以前,还须要先准备一个DOM标签(通常为div)做为容器,用于显示地图。java

<el-col style="width: calc(100% - 320px);padding-left: 20px">
    <div id="allmap" ref="allmap" :style="{ height: mapHandler.height + 'px' }"></div>
</el-col>

注:地图显示和其余内容显示不同,其余节点咱们给DOM标签或父标签设置了宽(100%)高(100%),标签会根据内容的宽高自行撑开节点显示。但地图不会,须要咱们明确地设定宽高值(不能用比较宽泛的100%)git

二、初始化地图

容器节点准备好之后,就能够进行地图的初始化了。(因为百度地图基类BMap在项目启动时,已被挂载到window对象上,故能够直接调用)api

const BMap = window.BMap;// 用常量存放BMap基类,便于其余地方调用,不用每次都去window对象上获取,也更易于理解
mounted() {
  this.initMap();
},
initMap() {
  this.mapInstance = new BMap.Map(this.$refs.allmap); // 初始化地图,建立Map实例,用全局变量存放Map实例,便于子组件或其余方法调用Map实例
  this.getCurrentPosition();

  this.mapInstance.addControl(new BMap.NavigationControl()); // 添加地图缩放比例组件
  this.mapInstance.addControl(new BMap.ScaleControl()); // 添加比例尺组件
  this.mapInstance.addControl(new BMap.OverviewMapControl()); // 添加全局查看组件(我的感受没啥用)
  this.mapInstance.addControl(new BMap.MapTypeControl()); // 添加地图类型控制(地图、卫星、三维)
},

// 获取本地位置信息(经纬度坐标、城市名称等),进行地图初始化
getCurrentPosition() {
  let that = this;
  let geolocation = new BMap.Geolocation(); // 获取本地位置经纬度坐标
  geolocation.getCurrentPosition(
    function(r) {
      that.mapInstance.centerAndZoom(
        new BMap.Point(r.longitude, r.latitude),
        13
      ); // 地图初始化,设置中心点坐标(本地)和地图缩放比例。Point也能够设定为一个固定值,如天安门():
      that.mapInstance.setCurrentCity(r.address.city); // 设置地图显示的城市(当前位置城市) 此项必须设置
      that.mapInstance.enableScrollWheelZoom(true); // 开启鼠标滚轮缩放
      that.loadingStatus = true;
    },
    { enableHighAccuracy: true }
  );
},

三、地图功能开发

在地图初始化完成之后,就能够根据实际须要进行功能开发了。post

相关文章
相关标签/搜索