使用vue3结合高德实现定位功能
导读:准备工作使用高德地图JS API实现定位功能需要去申请注册账号和key https://lbs.amap.com/api/javascript-api/guide/abc/prepare申请好key,在这里查阅 https://consol...
准备工作
- 使用高德地图JS API实现定位功能
- 需要去申请注册账号和key https://lbs.amap.com/api/javascript-api/guide/abc/prepare
- 申请好key,在这里查阅 https://console.amap.com/dev/key/app
Vue项目
- 在index.html文件引入JS API 的入口脚本标签,并将其中key值=刚刚申请的key
script src="//webapi.amap.com/maps?v=2.0& key=自己申请的key"> /script>
- 在vue文件写入相应定位的代码
const getLocation = () => { // eslint-disable-next-line no-undef AMap.plugin('AMap.Geolocation', function () { var geolocation = new AMap.Geolocation({ // 是否使用高精度定位,默认:true enableHighAccuracy: true, // 设置定位超时时间,默认:无穷大 timeout: 10000 } ) //进行IP城市查询 geolocation.getCityInfo(function (status, result) { if (status == 'complete') { console.log(result, 'Ip获取的') } else { onError(result) } } ) //获取用户当前的精确位置信息(经纬度) geolocation.getCurrentPosition(function (status, result) { if (status == 'complete') { console.log(result) } else { onError(result) } } ) } ) //定位错误,使用另一方式定位 function onError (_data) { console.log('🚀 ~ file: AboutView.vue ~ line 72 ~ onError ~ _data', _data) getLngLatLocation() } } const getLngLatLocation = () => { //只获取城市级别的定位信息 AMap.plugin('AMap.CitySearch', function () { var citySearch = new AMap.CitySearch() citySearch.getLocalCity(function (status, result) { if (status === 'complete' & & result.info === 'OK') { // 查询成功,result即为当前所在城市信息 console.log('通过ip获取当前城市:', result) self.cityName = result.city self.cityCode = result.adcode var lnglat = result.rectangle.split('; ')[0].split(',') self.longitude = lnglat[0] self.latitude = lnglat[1] //逆向地理编码查询地理位置详细信息 AMap.plugin('AMap.Geocoder', function () { var geocoder = new AMap.Geocoder({ // city 指定进行编码查询的城市,支持传入城市名、adcode 和 citycode city: result.adcode } ) var lnglat = result.rectangle.split('; ')[0].split(',') geocoder.getAddress(lnglat, function (status, data) { if (status === 'complete' & & data.info === 'OK') { // result为对应的地理位置详细信息 console.log(data, '地理位置') } } ) } ) } else { } } ) } ) } getLocation()
- 这个时候会发现vue页面会报AMap is not defined
- 解决办法,在根目录下新建vue.config.js文件
configureWebpack: { externals: { 'AMap': 'AMap' // 高德地图配置 } }
- 在需要获取定位的页面,引入AMap
import AMap from 'AMap'
- 然后重启项目,就可以看到页面不报警告了
- 这个时候就可以看到页面定位的信息了
- 这样定位这个功能即可实现了
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: 使用vue3结合高德实现定位功能
本文地址: https://pptw.com/jishu/3423.html