当前位置: 代码迷 >> 综合 >> mapbox 绘制虚线
  详细解决方案

mapbox 绘制虚线

热度:77   发布时间:2023-10-17 07:02:04.0
<!DOCTYPE html>
<html><head><meta charset='utf-8' /><title>添加 GeoJSON 线</title><meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' /><script src='https://api.tiles.mapbox.com/mapbox-gl-js/v1.1.1/mapbox-gl.js'></script><link href='https://api.tiles.mapbox.com/mapbox-gl-js/v1.1.1/mapbox-gl.css' rel='stylesheet' /><style>body {margin: 0;padding: 0;}#map {position: absolute;top: 0;bottom: 0;width: 100%;}</style>
</head><body><div id='map'></div><script>mapboxgl.accessToken ='pk.eyJ1IjoibHh0aWFudGlhbiIsImEiOiJjaXd2ZjlkYnQwMTZvMnRtYWZnM2lpbHFvIn0.ef3rFZTr9psmLWahrqap2A';var map = new mapboxgl.Map({container: 'map',style: 'mapbox://styles/mapbox/streets-v11',center: [-122.486052, 37.830348],zoom: 15});let coordinates = [],layerActive = false;map.on('click', (e) => addLayer(e))map.on('mousemove', (e) => updateLayer(e))function addLayer(e) {if (layerActive) {removeLayer();layerActive = !layerActive;return;}const { lat, lng } = e.lngLat;coordinates[0] = [lng, lat];map.addSource('sourceId', {type: 'geojson',data: {"type": "Feature","properties": {},"geometry": {"type": "LineString","coordinates": coordinates}}});map.addLayer({"id": "route","type": "line","source": "sourceId","layout": {"line-join": "round","line-cap": "round"},"paint": {"line-color": "#888","line-width": 8,"line-dasharray": [2, 4]}});layerActive = !layerActive;}function updateLayer(e) {const {lat,lng} = e.lngLat;coordinates[1] = [lng, lat];const datas = {"type": "Feature","properties": {},"geometry": {"type": "LineString","coordinates": coordinates}}if (map.getSource('sourceId')) {map.getSource('sourceId').setData(datas);}}function removeLayer() {if (map.getLayer('route')) {map.removeLayer('route');}if (map.getSource('sourceId')) {map.removeSource('sourceId');}}</script></body></html>