加载地图 API
https://lbs.qq.com/webApi/jav...
其中,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));
根据地址获取坐标
地址解析类用于在地址和经纬度之间进行转换的服务
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, // 隐藏所有控件
}