- A+
所属分类:Web前端
🧑💻 写在开头
点赞 + 收藏 === 学会🤣🤣🤣
不FQ也能使用的地图还有Mapbox
安装
npm install --save axios
npm install --save mapbox-gl
npm install --save @mapbox/mapbox-gl-directions
使用
import mapboxgl from 'mapbox-gl';
import 'mapbox-gl/dist/mapbox-gl.css';
import MapboxDirections from '@mapbox/mapbox-gl-directions/dist/mapbox-gl-directions';
import '@mapbox/mapbox-gl-directions/dist/mapbox-gl-directions.css';
1.API实际地址转换经纬度
geocoderAddress (address) { return new Promise((resolve) => { axios({ url: `https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(address)}.json`, method: 'GET', params: { access_token: mapboxgl.accessToken } }).then(res => { if (res.status == 200) { let center = null; res.data.features.map(p => { if (!center) { center = p.center; } }) resolve(center); } }) }) }
2.初始化地图
const origin = await this.geocoderAddress(this.origin) const destination = await this.geocoderAddress(this.destination) this.map = new mapboxgl.Map({ container: 'mapboxId', style: 'mapbox://styles/mapbox/streets-v11', center: [(origin[0] + destination[0])/2, (origin[1] + destination[1])/2], zoom: 7.5, antialias: true, // 抗锯齿 });
添加全局显示控件
this.map.addControl(new mapboxgl.FullscreenControl());;
3.添加轨迹路线
this.map.on('load', () => { // 获取主图色 const primary = getComputedStyle(document.documentElement).getPropertyValue('--el-color-primary'); const themeColor = (primary.includes(',') ? `rgba(${primary}, 1)` : primary) || '#4361EE'; // 规划路线 this.directions = new MapboxDirections({ accessToken: mapboxgl.accessToken, unit: 'metric', // metric | imperial interactive: false, profile: 'mapbox/driving', controls: { inputs: false, instructions: false, profileSwitcher: false } }); this.map.addControl(this.directions, 'top-left'); this.directions.setOrigin(origin); // 设置起点的经纬度 this.directions.setDestination(destination); // 设置起点的经纬度
轨迹线的样式修改
// MapboxDirections 对象里加属性styles styles: [ { 'id': 'directions-route-line-casing', 'type': 'line', 'source': 'directions', 'layout': { 'line-cap': 'round', 'line-join': 'round' }, 'paint': { 'line-color': '#fff', 'line-width': 2, }, 'filter': [ 'all', ['in', '$type', 'LineString'], ['in', 'route', 'selected'] ] }, { 'id': 'directions-route-line', 'type': 'line', 'source': 'directions', 'layout': { 'line-cap': 'butt', 'line-join': 'round' }, 'paint': { 'line-color': { property': 'congestion', 'type': 'categorical', 'default': themeColor, 'stops': [ ['unknown', themeColor], ['low', themeColor], ['moderate', '#f09a46'], ['heavy', '#e34341'], ['severe', '#8b2342'] ] }, 'line-width': 7 } }, { 'id': 'directions-origin-point', 'type': 'circle', 'source': 'directions', 'paint': { 'circle-radius': 16, 'circle-color': '#f09a46' }, 'filter': [ 'all', ['in', '$type', 'Point'], ['in', 'marker-symbol', 'A'] ] }, { 'id': 'directions-destination-point', 'type': 'circle', 'source': 'directions', 'paint': { 'circle-radius': 16, 'circle-color': '#8b2342' }, 'filter': [ 'all', ['in', '$type', 'Point'], ['in', 'marker-symbol', 'B'] ] } ]
4.计算起始点的距离
this.directions.on('route', (event) => { // console.log(event.route); // 输出路线信息 // 计算距离为整数 const distance = Math.round(event.route[0].distance/1000 || 0); const distanceMI = Math.round(event.route[0].distance * 0.62137/1000 || 0); // 格式化公里 this.distanceMatrix = distance ? `${numberFormat(distance)} KM` : ''; // 格式化英里 if (this.unit == 'imperial') { this.distanceMatrix = distanceMI ? `${numberFormat(distanceMI)} MILES` : ''; } }); // 格式化函数 export const numberFormat = (num) => { return num.toString().replace(/B(?=(d{3})+(?!d))/g, ",") }
5.效果
6.HTML简易代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Mapbox Route from Tiananmen to The White House with Markers</title> <!-- 引入Mapbox GL JS的CSS文件 --> <link href='https://api.mapbox.com/mapbox-gl-js/v2.15.0/mapbox-gl.css' rel='stylesheet' /> <!-- 引入Mapbox GL JS的JavaScript文件 --> <script src='https://api.mapbox.com/mapbox-gl-js/v2.15.0/mapbox-gl.js'></script> </head> <body> <div id="map" style="width: 100%; height: 600px;"></div> <script> // 设置你的Mapbox访问令牌 mapboxgl.accessToken = '你申请的key'; // 创建地图实例 const map = new mapboxgl.Map({ container: 'map', style: 'mapbox://styles/mapbox/streets-v12', center: [0, 0], pitch: 21, // 倾斜度 maxZoom: 18, minZoom: 3, zoom: 7.5, attributionControl: false // 右下角标识 }); // 定义天安门的坐标(示例坐标,实际可根据准确位置调整) const tiananmenCoords = [-77.03653, 39.90882]; // 定义白宫的坐标(示例坐标,实际可根据准确位置调整) const whiteHouseCoords = [-77.03653, 38.89773]; // 创建一个包含起点和终点的GeoJSON对象来表示路线 const routeGeoJSON = { "type": "Feature", "properties": {}, "geometry": { "type": "LineString", "coordinates": [tiananmenCoords, whiteHouseCoords] } }; // 当地图加载完成后添加路线图层及标记 map.on('load', () => { // 添加一个数据源来存储路线数据 map.addSource('route', { "type": "geojson", "data": routeGeoJSON }); // 添加一个图层来渲染路线 map.addLayer({ "id": "route-layer", "type": "line", "source": "route", "layout": { "line-join": "round", "line-cap": "round" }, "paint": { "line-color": "blue", "line-width": 5 } }); // 添加天安门标记(标记为A) const tiananmenMarker = new mapboxgl.Marker({ color: "red" }) .setLngLat(tiananmenCoords) .setPopup(new mapboxgl.Popup({ offset: 25 }) .setText('A - 北京天安门')) .addTo(map); // 添加白宫标记(标记为B) const whiteHouseMarker = new mapboxgl.Marker({ color: "green" }) .setLngLat(whiteHouseCoords) .setPopup(new mapboxgl.Popup({ offset: 25 }) .setText('B - 美国白宫')) .addTo(map); // 将地图视图中心定位到路线的大致中心位置 map.flyTo({ center: [(tiananmenCoords[0] + whiteHouseCoords[0]) / 2, (tiananmenCoords[1] + whiteHouseCoords[1]) / 2] }); }); </script> </body> </html>