简体   繁体   中英

How do I use multiple lines in a single layer in mapbox-gl-js?

Mapbox uses source and layer to draw circle, line etc on the map. I have difficulty in understanding the source and layer id. As i can see through examples and tutorials that, a layer defines how the data should be displayed on the map, and a source defines the data for that layer.

I could have multiple sources and layers on the map.

I want to create multiple line layer on the map, so i did this.

map.addSource('11111111',{
                'type':'geojson',
                'data':{
                    'type':'Feature',
                    'properties':{},
                    'geometry':{
                        'type':'LineString',
                        'coordinates':[
                            [76.993894,31.781929]
                        ]
                    }
                }
            });
    
            map.addLayer({
                'id': '11111111',
                'type': 'line',
                'source': '11111111',
                'layout': {
                'line-join': 'round',
                'line-cap': 'round'
                },
                'paint': {
                'line-color': 'red',
                'line-width': 4
                }
            });

Here addSource method take an source id (11111111) . How can i add multiple line sources in one layer, because each sources must have unique id.

You can have multiple lines in a single source by using a feature collection .

map.addSource('multiple-lines-source', {
  'type': 'geojson',
  'data': {
    'type': 'FeatureCollection',
    'features': [
      {
        'type': 'Feature',
        'properties': {},
        'geometry': {
          'type': 'LineString',
          'coordinates': [
            [-104.4140625, 43.32517767999296],
            [-58.35937499999999, -9.79567758282973]
          ]
        }
      },
      {
        'type': 'Feature',
        'properties': {},
        'geometry': {
          'type': 'LineString',
          'coordinates': [
            [20.390625, 10.487811882056695],
            [15.468749999999998, 49.83798245308484]
          ]
        }
      }
    ]
  }
});

Here is a working example: https://jsfiddle.net/oh8Ld1ry/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM