如题
接到新的需求决定使用腾讯地图的定位
注册腾讯地图的步骤这里就不说了
按照传统的方法,如果是vue项目的话
我们多数会在index.html中直接引入腾讯地图定位的js
<script type="text/javascript" src="https://mapapi.qq.com/web/mapComponents/geoLocation/v/geolocation.min.js"></script>
但是由于我是在开发项目的单一组件,我无法得到index.html文件,这时候我们就可以动态引入,vue或者uniapp写h5都可以参考
created() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://mapapi.qq.com/web/mapComponents/geoLocation/v/geolocation.min.js";
document.getElementsByTagName('head')[0].appendChild(script);
},
我们在created生命周期中引入,接下来我们写获取定位的js函数,并在mounted中调用
getLocationByqqMap(){ //调用定位
let geolocation = new qq.maps.Geolocation("你的序列号", "myapp")
geolocation.getLocation(this.showPosition,this.showErr,{timeout: 2000})
},
showPosition(position) { //成功的回调
console.log(position)
},
showErr(){ //显示错误
console.log("err")
},
在mounted中使用
mounted() {
this.getLocationByqqMap()
}
好了,我们来看看结果
。。。报错了
说 ‘qq’ is no defined
这时候我习惯给这个this.getLocationByqqMap()用settimeout一下
成功了
很明显,是因为动态引入的js还没有引入完成,找不到 new qq.maps.Geolocation这个对象
那这样有什么办法呢,总不能一直用settimeout吧?
我们可以用setInterval
mounted() {
let getlocal = setInterval(()=>{
this.getLocationByqqMap()
if(this.isgetlocat == true) { // 设置一个停止的标志变量
clearInterval(getlocal);
}
}, 100);
}
原理就是在mounted中每隔100ms我们执行一下这个获取定位的函数,在获取到定位后,我们改变标志变量,然后清除掉这个循环的定时器
vue在某些情况下,使用setInterval这样的做法来获取未加载渲染完成的dom节点也是可以的