map.on('style.load',()=>{map.addSource('line',{type:'geojson',lineMetrics:true,data:{type:'LineString',coordinates:[[2.293389857555951,48.85896319631851],[2.2890810326441624,48.86174223718291]]}});map.addLayer({id:'line',source:'line',type:'line',paint:{'line-width':12,// The `*-emissive-strength` properties control the intensity of light emitted on the source features.// To enhance the visibility of a line in darker light presets, increase the value of `line-emissive-strength`.'line-emissive-strength':0.8,'line-gradient':['interpolate',['linear'],['line-progress'],0,'red',1,'blue']}});});
2.3. 配置一个带有 slot 的 style
map.addSource('urban-areas',{'type':'geojson','data':'https://docs.mapbox.com/mapbox-gl-js/assets/ne_50m_urban_areas.geojson'});map.addLayer({'id':'urban-areas-fill','type':'fill',// This property allows you to identify which `slot` in// the Mapbox Standard your new layer should be placed in (`bottom`, `middle`, `top`).'slot':'middle','source':'urban-areas','layout':{},'paint':{'fill-color':'#f08','fill-opacity':0.4}});
2.4. 创建一个自定义 style 的 layer 类实现 WebGL 内容
const map =newmapboxgl.Map({container:'map',// container IDstyle:'mapbox://styles/mapbox/streets-v12',// style URLcenter:[-74.5,40],// starting position [lng, lat]zoom:9,// starting zoom});// create a custom style layer to implement the WebGL contentconst highlightLayer ={id:'highlight',type:'custom',// method called when the layer is added to the map// https://docs.mapbox.com/mapbox-gl-js/api/#styleimageinterface#onaddonAdd:function(map, gl){// create GLSL source for vertex shaderconst vertexSource =`uniform mat4 u_matrix;attribute vec2 a_pos;void main() {gl_Position = u_matrix * vec4(a_pos, 0.0, 1.0);}`;// create GLSL source for fragment shaderconst fragmentSource =`void main() {gl_FragColor = vec4(1.0, 0.0, 0.0, 0.5);}`;// create a vertex shaderconst vertexShader = gl.createShader(gl.VERTEX_SHADER);gl.shaderSource(vertexShader, vertexSource);gl.compileShader(vertexShader);// create a fragment shaderconst fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);gl.shaderSource(fragmentShader, fragmentSource);gl.compileShader(fragmentShader);// link the two shaders into a WebGL programthis.program = gl.createProgram();gl.attachShader(this.program, vertexShader);gl.attachShader(this.program, fragmentShader);gl.linkProgram(this.program);this.aPos = gl.getAttribLocation(this.program,'a_pos');// define vertices of the triangle to be rendered in the custom style layerconst helsinki = mapboxgl.MercatorCoordinate.fromLngLat({lng:25.004,lat:60.239});const berlin = mapboxgl.MercatorCoordinate.fromLngLat({lng:13.403,lat:52.562});const kyiv = mapboxgl.MercatorCoordinate.fromLngLat({lng:30.498,lat:50.541});// create and initialize a WebGLBuffer to store vertex and color datathis.buffer = gl.createBuffer();gl.bindBuffer(gl.ARRAY_BUFFER,this.buffer);gl.bufferData(gl.ARRAY_BUFFER,newFloat32Array([helsinki.x,helsinki.y,berlin.x,berlin.y,kyiv.x,kyiv.y]),gl.STATIC_DRAW);},// method fired on each animation frame// https://docs.mapbox.com/mapbox-gl-js/api/#map.event:renderrender:function(gl, matrix){gl.useProgram(this.program);gl.uniformMatrix4fv(gl.getUniformLocation(this.program,'u_matrix'),false,matrix);gl.bindBuffer(gl.ARRAY_BUFFER,this.buffer);gl.enableVertexAttribArray(this.aPos);gl.vertexAttribPointer(this.aPos,2, gl.FLOAT,false,0,0);gl.enable(gl.BLEND);gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);gl.drawArrays(gl.TRIANGLE_STRIP,0,3);}};// add the custom style layer to the map
map.on('load',()=>{map.addLayer(highlightLayer,'building');});
2.5. 添加Marker
// Create a default Marker and add it to the map.const marker1 =newmapboxgl.Marker().setLngLat([12.554729,55.70651]).addTo(map);
2.6. 添加 geojson 格式的 point
map.addImage('custom-marker', image);// Add a GeoJSON source with 2 points
map.addSource('points',{'type':'geojson','data':{'type':'FeatureCollection','features':[{// feature for Mapbox DC'type':'Feature','geometry':{'type':'Point','coordinates':[-77.03238901390978,38.913188059745586]},'properties':{'title':'Mapbox DC'}},{// feature for Mapbox SF'type':'Feature','geometry':{'type':'Point','coordinates':[-122.414,37.776]},'properties':{'title':'Mapbox SF'}}]}});// Add a symbol layer
map.addLayer({'id':'points','type':'symbol','source':'points','layout':{'icon-image':'custom-marker',// get the title name from the source's "title" property'text-field':['get','title'],'text-font':['Open Sans Semibold','Arial Unicode MS Bold'],'text-offset':[0,1.25],'text-anchor':'top'}});
2.7. 添加 geojson 格式的 line_string
// Create a default Marker and add it to the map.
map.addSource('route',{'type':'geojson','data':{'type':'Feature','properties':{},'geometry':{'type':'LineString','coordinates':[[-122.483696,37.833818],[-122.483482,37.833174],[-122.483396,37.8327],[-122.483568,37.832056],[-122.48404,37.831141],[-122.48404,37.830497],[-122.483482,37.82992],[-122.483568,37.829548],[-122.48507,37.829446],[-122.4861,37.828802],[-122.486958,37.82931],[-122.487001,37.830802],[-122.487516,37.831683],[-122.488031,37.832158],[-122.488889,37.832971],[-122.489876,37.832632],[-122.490434,37.832937],[-122.49125,37.832429],[-122.491636,37.832564],[-122.492237,37.833378],[-122.493782,37.833683]]}}});map.addLayer({'id':'route','type':'line','source':'route','layout':{'line-join':'round','line-cap':'round'},'paint':{'line-color':'#000','line-width':20}});
2.8. 添加 geojson 格式的 ploygon
map.addSource('maine',{'type':'geojson','data':{'type':'Feature','geometry':{'type':'Polygon',// These coordinates outline Maine.'coordinates':[[[-67.13734,45.13745],[-66.96466,44.8097],[-68.03252,44.3252],[-69.06,43.98],[-70.11617,43.68405],[-70.64573,43.09008],[-70.75102,43.08003],[-70.79761,43.21973],[-70.98176,43.36789],[-70.94416,43.46633],[-71.08482,45.30524],[-70.66002,45.46022],[-70.30495,45.91479],[-70.00014,46.69317],[-69.23708,47.44777],[-68.90478,47.18479],[-68.2343,47.35462],[-67.79035,47.06624],[-67.79141,45.70258],[-67.13734,45.13745]]]}}});map.addLayer({'id':'maine','type':'fill','source':'maine',// reference the data source'layout':{},'paint':{'fill-color':'#0080ff',// blue color fill'fill-opacity':0.5}});
2.9. 在指定 layer 的上方添加图层
const layers = map.getStyle().layers;// Find the index of the first symbol layer in the map style.let firstSymbolId;for(const layer of layers){console.log('laye = ',layer.id,' type = ',layer.type);if(layer.type ==='symbol'){firstSymbolId = layer.id;break;}}map.addSource('urban-areas',{'type':'geojson','data':'https://docs.mapbox.com/mapbox-gl-js/assets/ne_50m_urban_areas.geojson'});
map.addLayer({'id':'urban-areas-fill','type':'fill','source':'urban-areas','layout':{},'paint':{'fill-color':'#f08','fill-opacity':0.4}// This is the important part of this example: the addLayer// method takes 2 arguments: the layer as an object, and a string// representing another layer's name. If the other layer// exists in the style already, the new layer will be positioned// right before that layer in the stack, making it possible to put// 'overlays' anywhere in the layer stack.// Insert the layer beneath the first symbol layer.},firstSymbolId
);
// Add a new vector tile source with ID 'mapillary'.
map.addSource('mapillary',{'type':'vector','tiles':['https://tiles.mapillary.com/maps/vtp/mly1_public/2/{z}/{x}/{y}?access_token=MLY|4142433049200173|72206abe5035850d6743b23a49c41333'],'minzoom':6,'maxzoom':14});
map.addLayer({'id':'mapillary',// Layer ID'type':'line','source':'mapillary',// ID of the tile source created above// Source has several layers. We visualize the one with name 'sequence'.'source-layer':'sequence','layout':{'line-cap':'round','line-join':'round'},'paint':{'line-opacity':0.6,'line-color':'rgb(53, 175, 109)','line-width':2}},'road-label-simple'// Arrange our new layer beneath labels and above roads);
2.9. vector
map.addSource('mapbox-terrain',{type:'vector',// Use any Mapbox-hosted tileset using its tileset id.// Learn more about where to find a tileset id:// https://docs.mapbox.com/help/glossary/tileset-id/url:'mapbox://mapbox.mapbox-terrain-v2'});
map.addLayer({'id':'terrain-data','type':'line','source':'mapbox-terrain','source-layer':'contour','layout':{'line-join':'round','line-cap':'round'},'paint':{'line-color':'#ff69b4','line-width':1}},'road-label-simple'// Add layer below labels);
2.10. heatmap
<template><div id="map"></div></template><script>import'mapbox-gl/dist/mapbox-gl.css';import mapboxgl from'mapbox-gl';// or "const mapboxgl = require('mapbox-gl');"
mapboxgl.accessToken ='pk.eyJ1IjoiZ2lzZXJqaWFuZyIsImEiOiJjbHJ3Ym1nZzYwdTI2Mml1b3FzN3RlZmRrIn0.Sy_jGFu4prk99Udfa6AgkQ';import{ nextTick, onMounted }from'vue'exportdefault{name:'BasicMapContainer',setup(){onMounted(()=>{const map =newmapboxgl.Map({container:'map',// Choose from Mapbox's core styles, or make your own style with Mapbox Studiostyle:'mapbox://styles/mapbox/light-v11',zoom:8,center:[-74.5447,40.6892]});map.on('load',()=>{// Add a geojson point source.// Heatmap layers also work with a vector tile source.map.addSource('earthquakes',{'type':'geojson','data':'https://docs.mapbox.com/mapbox-gl-js/assets/earthquakes.geojson'});map.addLayer({'id':'earthquakes-heat','type':'heatmap','source':'earthquakes','maxzoom':9,'paint':{// Increase the heatmap weight based on frequency and property magnitude'heatmap-weight':['interpolate',['linear'],['get','mag'],0,0,6,1],// Increase the heatmap color weight weight by zoom level// heatmap-intensity is a multiplier on top of heatmap-weight'heatmap-intensity':['interpolate',['linear'],['zoom'],0,1,9,3],// Color ramp for heatmap. Domain is 0 (low) to 1 (high).// Begin color ramp at 0-stop with a 0-transparancy color// to create a blur-like effect.'heatmap-color':['interpolate',['linear'],['heatmap-density'],0,'rgba(33,102,172,0)',0.2,'rgb(103,169,207)',0.4,'rgb(209,229,240)',0.6,'rgb(253,219,199)',0.8,'rgb(239,138,98)',1,'rgb(178,24,43)'],// Adjust the heatmap radius by zoom level'heatmap-radius':['interpolate',['linear'],['zoom'],0,2,9,20],// Transition from heatmap to circle layer by zoom level'heatmap-opacity':['interpolate',['linear'],['zoom'],7,1,9,0]}},'waterway-label');map.addLayer({'id':'earthquakes-point','type':'circle','source':'earthquakes','minzoom':7,'paint':{// Size circle radius by earthquake magnitude and zoom level'circle-radius':['interpolate',['linear'],['zoom'],7,['interpolate',['linear'],['get','mag'],1,1,6,4],16,['interpolate',['linear'],['get','mag'],1,5,6,50]],// Color circle by earthquake magnitude'circle-color':['interpolate',['linear'],['get','mag'],1,'rgba(33,102,172,0)',2,'rgb(103,169,207)',3,'rgb(209,229,240)',4,'rgb(253,219,199)',5,'rgb(239,138,98)',6,'rgb(178,24,43)'],'circle-stroke-color':'white','circle-stroke-width':1,// Transition from heatmap to circle layer by zoom level'circle-opacity':['interpolate',['linear'],['zoom'],7,0,8,1]}},'waterway-label');});})return{}}}</script><style scoped>
#map {position: absolute; top:0; bottom:0; width:99.1%;}</style>
map =newmapboxgl.Map({container:'map',// Choose from Mapbox's core styles, or make your own style with Mapbox Studiostyle:'mapbox://styles/mapbox/satellite-streets-v12',zoom:0,center:[0,1],projection:{name:'lambertConformalConic',center:[0,30],parallels:[30,30]}});