随笔 - 210  文章 - 0 评论 - 0 阅读 - 61374
< 2025年2月 >
26 27 28 29 30 31 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 1
2 3 4 5 6 7 8

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

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

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<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

1
2
3
4
5
6
7
8
9
10
11
12
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   鲤斌  阅读(238)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 【.NET】调用本地 Deepseek 模型
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
点击右上角即可分享
微信分享提示