百度地图在Https协议的项目中不能访问

Vue项目开发中,要使用百度地图API SDK

需求1:获取当前城市名称;

需求2:获取当前城市坐标(经度,纬度)

方案:

  ① 在代码中引入 百度地图API SDK

 <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=你百度开放平台申请的秘钥"></script>

  在此需注意:引入sdk时使用的是 `http`协议的,项目上线使用的是`https`协议会到时地图不能使用,导致如下报错

    

           

  解决方案:

<script type="text/javascript" src="https://api.map.baidu.com/api?v=2.0&ak=你百度开放平台申请的秘钥"></script>

  ② 在项目中安装  `bmap` 依赖

npm intsall bmap --save

  ③ 在组件内写入如下方法,并调用

// 定位当前城市坐标
    getCurrentCityCoordinates() {
      let geolocation = new BMap.Geolocation()
      //弹出地理授权
      let that = this
      geolocation.getCurrentPosition(
        function(res) {
          console.log(res)
          if (this.getStatus() == BMAP_STATUS_SUCCESS) {
            that.$message.success({
              content: '定位成功',
            })
            that.center.lng = res.point.lng
            that.center.lat = res.point.lat
          } else {
            that.$message.error({
              content: 'baidu return failed',
            })
          }
        }, //获取失败时候的回调
        function(res) {
          console.log(res)
        }
      )
    },

    在获取定位成功后,打印的 `console.log(r)` 结果如下,

原文地址:https://www.cnblogs.com/spaortMan/p/13926858.html