首先进入 百度地图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属性,此为跨域获取的数据 }) } |
实现效果
访问的时候必须用上方白名单中的域名进行访问,否则无法进行定位
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 【.NET】调用本地 Deepseek 模型
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库