实现Mapbox中定位功能的关键在于通过高德地图API获取当前位置信息,并将这些信息转换为经纬度坐标。
首先,通过调用高德地图的IP定位接口获取所在城市信息;其次,利用城市信息调用地理逆编码接口获取经纬度坐标;最后,使用Mapbox的flyTo方法将地图定位到指定坐标。整个过程中涉及了多个API的调用和数据的处理,如字符串的拼接、JSON的解析等,以实现准确的定位效果。

实现定位功能
class MyLocationControl {
onAdd(map) {
this._map = map;
this._container = document.createElement("div");
this._container.className = "mapboxgl-ctrl my-location-control";
this._container.textContent = "定位";
return this._container;
}
onRemove() {
this._container.parentNode.removeChild(this._container);
this._map = undefined;
}
}
const myLocationControl = new MyLocationControl();
map.addControl(myLocationControl, "top-left");
const myLocationControlBtn = document.querySelector(".my-location-control");
myLocationControlBtn.onclick = function () {
// 获取当前的位置 navigator.geolocation.getCurrentPosition();
};
设置图标样式:
.my-location-control {
background-color: aqua;
border: 1px solid black;
border-radius: 5px;
padding: 4px;
}

使用高德API进行定位
找到高德API的IP定位接口,并发送请求,请求参数包括高德API key和默认IP地址,获取定位结果,并打印到控制台。

逆地理编码获取经纬度
使用高德API的逆地理编码接口,将城市名称转换为经纬度坐标。
使用flyTo或easeTo方法,将地图移动到当前位置,增加动画效果。
class MyLocationControl {
onAdd(map) {
this._map = map;
this._container = document.createElement("div");
this._container.className = "mapboxgl-ctrl my-location-control";
this._container.textContent = "定位";
return this._container;
}
onRemove() {
this._container.parentNode.removeChild(this._container);
this._map = undefined;
}
}
const GAODEKEY = "6306a665fdfd4bb5cac88647eb9dc34";
const myLocationControl = new MyLocationControl();
map.addControl(myLocationControl, "top-left");
const myLocationControlBtn = document.querySelector(".my-location-control");
myLocationControlBtn.onclick = async function () {
// 获取当前的位置 navigator.geolocation.getCurrentPosition()
const res = await fetch("https://restapi.amap.com/v3/ip?key=" + GAODEKEY);
const data = await res.json();
const _res = await fetch(
`https://restapi.amap.com/v3/geocode/geo?address=${data.city}&key=${GAODEKEY}`
);
const _data = await _res.json();
const lngLat = _data.geocodes[0].location.split(",");
lngLat.map((item) => Number(item));
map.flyTo({
center: lngLat,
});
};
