腾讯位置服务 JavaScript API

加载地图 API

https://lbs.qq.com/webApi/jav...

<script charset="utf-8" src="https://map.qq.com/api/js?v=2.exp&key=YOUR_KEY"></script>

其中,v参数是援用的版本号,目前腾讯地图提供两个版本,别离是v=1,v=2.exp,举荐应用2.exp,能够取得最新最快的反对。Key参数YOUR_KEY是Key鉴权中申请的key。

初始化

function initMap() {  const center = new window.qq.maps.LatLng(DefaultLatitude, DefaultLongitude);  const mapOptions = {    zoom: 12,    mapTypeId: window.qq.maps.MapTypeId.ROADMAP,    center: center  };  map = new window.qq.maps.Map(mapEle, mapOptions);  marker = new window.qq.maps.Marker({    position: center,    map: map  });}

marker标记

marker = new window.qq.maps.Marker({    position: center,    map: map,});

革除标记:

function clearMarker() {  if (marker && marker.getMap()) {    marker.setMap(null);  }}

增加地图点击事件

事件

点击地图事件

function clickMapListener() {  listener = window.qq.maps.event.addListener(map, "click", (event) => {    // 获取点击地位的地理坐标属性latLng    const { latLng } = event;    clearMarker();    marker = new window.qq.maps.Marker({      position: latLng,      map: map    });    const lng = Number(latLng.getLng());    const lat = Number(latLng.getLat());  });}

移除事件:

window.qq.maps.event.removeListener(listener)

批改地图中心点

地图显示管制

通过调用setCenter办法可对地图中心点进行批改
var map = new TMap.Map('container', { //初始化地图    center: new TMap.LatLng(39.984120,116.307484),  //设置地图初始中心点    zoom:11,   //设置地图缩放级别});//批改地图中心点map.setCenter(new TMap.LatLng(lat,lng));

依据地址获取坐标

地址解析 Geocoder

地址解析类用于在地址和经纬度之间进行转换的服务

官网 demo

function getCoordsFromAddress(address) {  if (!geocoder) {    geocoder = new window.qq.maps.Geocoder();  }  const trimAddress = address ? address.trim() : "";  const geoAddress = trimAddress || DefaultAddress;  geocoder.getLocation(geoAddress);  geocoder.setComplete((result) => {    const { location } = result.detail;    const { lng, lat } = location;    // console.log(lng, lat)    map.setCenter(location);    clearMarker();    marker = new window.qq.maps.Marker({      map: map,      position: location    });    });  geocoder.setError(() => {    // ...  });}

暗藏控件

const mapOptions = {    // ...    disableDefaultUI: true, // 暗藏所有控件}

Demo

https://codepen.io/ly023/pen/...