0
votes

I'm trying to add a layer of GeoJSON data onto a MapBox base map, but it won't work. I've tried a number of their tutorials like this one and this one, but they won't work.

This is my code:

var map = new mapboxgl.Map({
      container: 'themap',
      center: [-73.9939914, 40.7274072],
      zoom: 17,
      style: 'mapbox://styles/mapbox/streets-v9'
  });

  map.on('load', function () {

    map.addSource('plutodata', {
    type: 'geojson',
    url: 'http://url.geojson'
    });
   map.addLayer({
   id: 'pluto',
   type: 'fill',
   source: 'plutodata',
   'source-layer': 'plutodata',
       layout: {
         visibility: 'visible'
       },
       paint: {
         'fill-color': 'rgba(61,153,80,0.55)'
       }
    });
  });

The map loads, but the GeoJSON layer does not appear. Any ideas where I'm going wrong?

Full Solution:

tmcw's post below was the first step in fixing this issue. I added the COR-enabling headers to my .htaccess file. The second step was that the "url" property under map.addSource should have been "data." Now everything works.

2

2 Answers

2
votes

For Mapbox GL JS to load data from this server, it needs to use Cross-origin resource sharing, and this URL doesn't support that. You'll need to enable CORS on the server or the file to permit other servers to request data.

0
votes

You can upload your geojson as a tileset to Mapbox, then make a new layer in one of your styles, and enter your geojson tileset under the tab 'Layer from Data'. If, for instance, you called your new layer 'mygeojson' then you can call it in your .js, eg:

map.on('load', function() { map.addLayer({ 'id': 'mygeojson', 'source': 'composite', 'source-layer': 'mygeojson', 'type': 'fill', 'paint': { 'fill-color': '#f00' } }); });