一、注册成为腾讯地图开发者
https://lbs.qq.com/
创建新秘钥
https://lbs.qq.com/dev/console/key/manage
根据页面提示填写相关信息
复制你的秘钥
二、vue中index.html中里引入需要的js文件
注意填写你的密钥
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1.0 user-scalable=no" > <title>demo</title> </head> <script charset="utf-8" src="https://map.qq.com/api/js?v=2.exp&key=你的密钥"></script> <script src="https://map.qq.com/api/gljs?v=1.exp&key=你的密钥"></script> <script src="https://3gimg.qq.com/lightmap/components/geolocation/geolocation.min.js"></script> <body> <div id="app" style="background-color: antiquewhite;"> </div> </body> </html> <script> </script>
三、在需要位置服务的页面初始化地图并获取位置
写到methods:{}里边,
init() { //步骤:定义map变量 调用 qq.maps.Map() 构造函数 获取地图显示容器 //设置地图中心点 let lat, lng; var that = this; var geolocation = new qq.maps.Geolocation( "你的密钥", "myapp" ); var myLatlng; var geoloc = geolocation.getLocation( function (position) { lat = position.lat; lng = position.lng; myLatlng = new qq.maps.LatLng(lat, lng); //定义工厂模式函数 var myOptions = { zoom: 20, //设置地图缩放级别 center: myLatlng, //设置中心点样式 mapTypeId: qq.maps.MapTypeId.ROADMAP, //设置地图样式详情参见MapType }; //获取dom元素添加地图信息 var map = new qq.maps.Map( document.getElementById("container"), myOptions ); var listener = qq.maps.event.addListener(map, "click", function ( event ) { console.info("mouseup", event); that.latLng = event.latLng; setTimeout(function () { var lat = parseFloat(that.latLng.lat); var lng = parseFloat(that.latLng.lng); var latLng = new qq.maps.LatLng(lat, lng); //对指定经纬度进行解析 that.geocoder.getAddress(latLng); }, 50); }); that.geocoder = new qq.maps.Geocoder(); //设置服务请求成功的回调函数 that.geocoder.setComplete(function (result) { console.info("result", result); that.positionName = result.detail.address; that.locationDetails.address = result.detail.address; that.locationDetails.addressComponents = result.detail.addressComponents; that.locationDetails.location = result.detail.location; that.locationDetails.nearPois = result.detail.nearPois; that.show = false; map.setCenter(result.detail.location); var marker = new qq.maps.Marker({ map: map, position: result.detail.location, }); //点击Marker会弹出反查结果 qq.maps.event.addListener(marker, "click", function () { alert("坐标地址为: " + result.detail.location); that.$toast("result.detail.location"); }); }); //若服务请求失败,则运行以下函数 that.geocoder.setError(function () { alert("出错了,请输入正确的地址!!!"); }); }, null, { timeout: 500, failTipFlag: true } ); },
mounted() { this.init(); },
<div class="block" id="container" @ontouchend="choicemap"></div>