实现功能:使用百度地图获取IP地址,定位到当前位置
参考文档地址:MapVGL | 快速入门
一、在有外网的情况下,常规引入百度地图的方法如下:
1、在index.html中引入
<script src="//api.map.baidu.com/api?v=1.0&type=webgl&ak=你的密钥"></script>

2、引入以后,不需要其它操作即可以直接使用全局BMapGL。然后可以获取ip定位
//获取当前ip经纬度地址(百度地图),并进行定位
        _getIPxy() {
            const self = this
            self.$nextTick(() => {
                var geolocation = new BMapGL.Geolocation();
                geolocation.getCurrentPosition(function (r) {
                    if (this.getStatus() == BMAP_STATUS_SUCCESS) {//注意:这里的tihs不是全局的this
                        //正式代码
                        let locationX = r.longitude
                        let locationY = r.latitude
                        console.log("ip位置", r)
                    } else {
                        console.info('获取当前定位失败' + this.getStatus());
                    }
                });
            })
        }, 
二、上面方法一引入后BMapGL获取不到可以试试这种,但是需要安装mapvgl
1、安装mapvgl: npm install mapvgl
2、新建一个bMap.js(文件名随意)文件,用来设置你的百度密钥
//ak是你的百度密钥
export function BMPGL(ak) {
    return new Promise(function(resolve, reject) {
      window.init = function() {
        // eslint-disable-next-line
        resolve(BMapGL)
      }
      const script = document.createElement('script')
      script.type = 'text/javascript'
      script.src = `https://api.map.baidu.com/api?v=1.0&type=webgl&ak=${ak}&callback=init`
      script.onerror = reject
      document.head.appendChild(script)
    })
  } 

3、在vue中引入bMap.js,并设置ak,然后获取ip定位
import { BMPGL } from "./core/bMap.js";
BMapGL: null,
mapvglAK:"你的百度密钥",

设置百度地图密钥(可以放mounted中)
//初始化百度地图
            _initBMap(){
                const self = this
                BMPGL(self.mapvglAK).then(BMapGL =>{
                    self.BMapGL = BMapGL;
                })
            }, 
获取ip定位(注意:这里的self.BMapGL是data参数中自己定义的全局变量了,所以这里名称可以自己随意选取了,为了方便代码修改,最好是用BMapGL)
//获取当前ip经纬度地址(百度地图),并进行定位
			_getIPxy() {
				const self = this
				self.$nextTick(() => {
					var geolocation = new self.BMapGL.Geolocation();
					geolocation.getCurrentPosition(function(r) {
						if (this.getStatus() == BMAP_STATUS_SUCCESS) {
							//正式代码
							let locationX = r.longitude
							let locationY = r.latitude
							console.log("ip位置", r)
						} else {
							console.info('获取当前定位失败' + this.getStatus());
						}
					});
				})
			},
			 
                




![[INS-30014]无法检查指定的位置是否位于 CFS 上](https://img-blog.csdnimg.cn/direct/bed42dd1673c4e0291f2067e24148c5c.png)













