element使用腾讯位置服务
作者:langdi 来源: 发布时间:2022-05-02 19:00:37
1 先通过腾讯地图官方申请key
2 在vue的public下的index.html中添加:
<script charset="utf-8" src="https://map.qq.com/api/js?v=2.exp&key=申请的key&libraries=place"></script> <script type="text/javascript" src="https://3gimg.qq.com/lightmap/components/geolocation/geolocation.min.js"></script>
3.在要使用地图的vue页面
template中添加:
<div id="container"> <el-input class="search" v-model="input" type="text" id="place" placeholder="请输入地点"></el-input> </div>
css部分:
#container { width: 100%; height: 400px; } .search { width: 200px; position: absolute; right: 5px; top: 40px; z-index: 999; }
js中添加
let map, marker;
methods:
getMyLocation() { let geolocation = new qq.maps.Geolocation('申请的key', '应用名'); geolocation.getLocation(this.showPosition, this.showErr); }, showPosition(position) { this.position.latitude = position.lat; this.position.longitude = position.lng; this.position.city = position.city; this.setMapData(); }, //定位失败再请求定位 showErr() { console.log('定位失败,请重试!'); this.getMyLocation(); }, setMapData() { let myLatlng = new qq.maps.LatLng(this.position.latitude, this.position.longitude); let myOptions = { zoom: 15, center: myLatlng, mapTypeId: qq.maps.MapTypeId.ROADMAP }; //获取dom元素添加地图信息 map = new qq.maps.Map(document.getElementById('container'), myOptions); //给定位的位置添加图片标注 marker = new qq.maps.Marker({ position: myLatlng, map: map, draggable: true //允许鼠标拖动 }); this.mouseClick(); this.search(); }, mouseClick() { let that = this; qq.maps.event.addListener(map, 'click', function (event) { if(!marker) { marker = new qq.maps.Marker({ position: event.latLng, map: map }); return } marker.setPosition(event.latLng); that.position.longitude = event.latLng.lng.toFixed(6); that.position.latitude = event.latLng.lat.toFixed(6); }); }, search() { let ap = new window.qq.maps.place.Autocomplete(document.getElementById('place')); let keyword = ''; //调用Poi检索类。用于进行本地检索、周边检索等服务。 let searchService = new window.qq.maps.SearchService({ complete : function(results){ if(results.type === 'CITY_LIST') { searchService.setLocation(results.detail.cities[0].cityName); searchService.search(keyword); return; } let pois = results.detail.pois; let latlngBounds = new window.qq.maps.LatLngBounds(); for(let i = 0,l = pois.length;i < l; i++){ let poi = pois[i]; latlngBounds.extend(poi.latLng); let marker = new window.qq.maps.Marker({ map: map, position: poi.latLng }); marker.setTitle(poi.name); } map.fitBounds(latlngBounds); } }); //添加监听事件 window.qq.maps.event.addListener(ap, 'confirm', function(res){ keyword = res.value; searchService.search(keyword); }); }
credated中
this.getMyLocation();
data中
input: '', position: { longitude: 0,//经度 latitude:0,//纬度 city:'', }
通过以上步骤,完成页面集成腾讯位置服务,并通过地址名称关键词搜索地图的经纬度和定位,标注位置获取经纬度,初始化时根据ip获取所在城市位置等。
tips:后续尝试在dialog中显示地图控件 将地图vue组件化及一些更丰富的互动功能。