在最近開發的微信公眾號中,要實現一個打卡功能:
由於個人感覺微信SDK里面的地圖不太好用,所以使用了騰訊地圖。
在項目中引入騰訊地圖
1,需要登錄騰訊地圖網站,注冊一個賬戶,獲得一個key。
2,然后找到項目根目錄下面的index.html,引入需要使用到的js
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<script type="text/javascript" src="https://3gimg.qq.com/lightmap/components/geolocation/geolocation.min.js"></script>
</head>
<body>
<div id="app"></div>
</body>
</html>
3,項目根目錄--> src -->service文件夾下新建parking.js(文件名稱和路徑可以自定義,只需要在使用時能找到就可以了)
parking.js(文件里的key填自己申請的就可以了)
export function TMap() { return new Promise(function(resolve, reject) { window.init = function() { resolve(qq) } var script = document.createElement('script') script.type = 'text/javascript' script.src = 'https://map.qq.com/api/js?v=2.exp&callback=init&key=SI5BZ-RTZRQ-2YD52-GAIRP-Z2CBK-7SFIC' script.onerror = reject document.head.appendChild(script) }) }
使用地圖
1,引入parking.js
2,展示地圖的容器
3,獲取當前位置,並展示以當前位置為中心的地圖(注釋位置依舊填寫自己注冊的key)
先貼代碼
getMyLocation() { var geolocation = new qq.maps.Geolocation("SI5BZ-RTZRQ-2YD52-GAIRP-Z2CBK-7SFIC", "打卡"); geolocation.getIpLocation(this.showPosition, this.showErr); }, showPosition(position) { console.warn(position); this.latitude = position.lat; this.longitude = position.lng; this.city = position.city; this.mapTX(); }, showErr() { Toast({ message: '定位失敗,請稍后重試!', position:'center', }); // this.$router.back(-1); this.getMyLocation();//定位失敗再請求定位,測試使用 }, mapTX() { let that = this; // 根據地理位置坐標,展示地圖 TMap().then(qq => { var map = new qq.maps.Map(document.getElementById('container'), { //這里經緯度代表進入地圖顯示的中心區域 center: new qq.maps.LatLng(that.latitude,that.longitude), zoom: 15 }); var marker = new qq.maps.Marker({ map : map, position : new qq.maps.LatLng(that.latitude,that.longitude), }); // 獲取當前經緯度對應的地址 var getAdd = new qq.maps.Geocoder({ complete : function(result){ console.log(result); that.address = result.detail.address; } }); var latLng = new qq.maps.LatLng(that.latitude, that.longitude); getAdd.getAddress(latLng); //綁定單擊事件添加參數 qq.maps.event.addListener(map, 'click', function(event) {}) }) },
在showPosition(position)這個方法里面就會有位置信息,包括經緯度和地址。
然后根據這里的經緯度就可以調用mapTX()來繪制地圖了,但是因為我們需要展示當前定位的位置,而上面打印的並不精確,所以還需要根據獲取到當前經緯度對應的詳細地址:
只要獲取到了經緯度和詳細地址,我們就可以進行打卡了。
點擊事件
在地圖中是可以添加點擊事件的,但是由於這里不需要,所以上面沒有寫。關於點擊事件,主要就是獲取點擊位置的經緯度就可以繼續后續的操作。
打印上面代碼中點擊事件的event
也就是,我們是可以通過event.latLng.getLat()和event.latLng.getLng()獲取到經緯度的,如果還需要獲取點擊的位置,再調用上面getAdd.getAddress(latLng)方法,傳入點擊獲取的經緯度就可以了。