简体   繁体   中英

In Mapbox GL JS, can you pass coordinates to an external GeoJSON data source?

Can you pass coordinate values as variables when trying to retreive an external GeoJSON data source? Ideally I'd like to pass something like this, but it doesn't work for me.

map.addSource('geojsonpoints', {
    type: "geojson",
    data: 'http://myexample.com/pins?lat={lat}&lon={long}'
  });

I am able to pass Z, X, Y coordinates if I use Map Vector Tiles (mvt) as a source. ie This works:

  map.addSource('mapvectortiles', {
    'type': 'vector',
    'tiles': ['http://myexample.com/{z}/{x}/{y}'],

But I haven't figured out how to do it for a GeoJSON source. Anyone have any ideas if it is possible in n Mapbox GL JS?

FYI, I am able to generate the URL using the method below, but the problem is it doesn't refresh when I move the map, unlike vector tiles.

var lng = map.getCenter().lng
var lat = map.getCenter().lat
var url = 'http://myexample.com/pins?lat='+lat+'&lon='+lng
map.addSource('EPC', {
  type: "geojson",
  data: url
});

I use GeoJSON to draw Tiles on the map

this is a sample GeoJSON:

    { "type": "FeatureCollection", 
  "features": [
    { "type": "Feature",
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [ 
            [4.342254780676343, 50.89533552689166], 
            [4.342254780676343, 50.89443721160754], 
            [4.340830581474948, 50.89443721160754],
            [4.340830581474948, 50.89533552689166],
            [4.342254780676343, 50.89533552689166]
         ]
        ]
      },
      "properties": {}
    }    
  ]
}

after all you have to add the source and add the layer

add Source:

const sourceJson: GeoJSONSourceRaw = {
        type: 'geojson',
        data: data as FeatureCollection
    };
    map.addSource(sourceId, sourceJson)

data is your json file

add Layer:

 const layer: FillLayer =  {
        id: sourceId,
        source: sourceId,
        type: 'fill',
        paint: {
            'fill-color': color,
            'fill-opacity': opacity 
        }
    }
        
    this.map.addLayer(layer);

There are two parts to your question:

  1. Update the data source when the map is moved
  2. Use the map's extent as part of the GeoJSON source's URL.

You have part 2 under control, so:

Update the data source when the map is moved

  1. Use map.on('moveend', ...
  2. Use map.getSource(...).setData(...)

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