首先进入 百度地图API 申请百度定位

使用的域名必须填写,否则无法定位

vue前端代码

<template>
  <div>城市:{{city}}</div>
</template>

<script>
import axios from "axios";
import { MP } from "../assets/map.js";
export default {
  mounted() {
    this.getCity();
  },

  data() {
    return {
      //定位城市
      ak: "wqDj1PlCmWtGwvhifXPlww5sp444rdsxomer", //秘钥
      city: ""
    };
  },
  methods: {
    //百度定位城市
    getCity() {
      this.$nextTick(() => {
        MP(this.ak).then(BMap => {
          //在此调用api
          var geolocation = new BMap.Geolocation();
          //  alert("城市:"+ this.city);
          geolocation.getCurrentPosition(a => {
            this.city = a.address.city;
            alert("城市:" + this.city);
          });
        });
      });
    },

    findAll() {}
  }
};
</script>

 
<style scoped>
</style>

讲百度地图API中的AK进行复制到代码中

在assets中创建map.js

export function MP(ak) {
    return new Promise(function (resolve, reject) {
        window.onload = function () {
            resolve(window.BMap)//插入script标签后 会在window上挂一BMap属性,此为跨域获取的数据
        };
        var script = document.createElement("script");
        script.type = "text/javascript";
        script.src = "http://api.map.baidu.com/api?v=2.0&ak=" + ak + "&callback=init";
        script.onerror = reject;
        document.head.appendChild(script);//插入此标签后 会在window上挂一BMap属性,此为跨域获取的数据
    })
}

实现效果

访问的时候必须用上方白名单中的域名进行访问,否则无法进行定位

 

posted on 2023-02-25 19:59  鲤斌  阅读(253)  评论(0)    收藏  举报