Search code examples
javascriptjquerymapboxgeojson

How can I update GeoJSON on my mapbox map after it has been created?


I have this html:

<div id="clickthis"><p>addGeoJSON</p></div>
<div id='raw'></div>
<div id='map'></div>

and this is my javascript code:

var geojson = [
  {
    "type": "Feature",
    "geometry": {
      "type": "Point",
      "coordinates": [-77.03238901390978,38.913188059745586]
    },
    "properties": {
      "title": "Mapbox DC",
      "description": "1714 14th St NW, Washington DC",
      "marker-color": "#fc4353",
      "marker-size": "large",
      "marker-symbol": "monument"
    }
  },
  {
    "type": "Feature",
    "geometry": {
      "type": "Point",
      "coordinates": [-122.414, 37.776]
    },
    "properties": {
      "title": "Mapbox SF",
      "description": "155 9th St, San Francisco",
      "marker-color": "#fc4353",
      "marker-size": "large",
      "marker-symbol": "harbor"
    }
  }
];
L.mapbox.accessToken = 'pk.eyJ1IjoibWFwcGllc3RpY2tlciIsImEiOiJIn0.IgCoorxIUvE0CjcPriROeQ';
var map = L.mapbox.map('map', 'mappiesticker.kh78ogof').setView([34, -118.50], 9);

$('#clickthis').click(function(){
  alert('alkr');
  dataLayer = L.mapbox.featureLayer(geojson);
  dataLayer.addTo(map);
})

The alert fires when I click that div, but nothing else happens. I tried using the .setGeoJSON function but it returned undefined. I concluded that thats only used when you are creating the map, not adding GeoJSON after its creation


Solution

  • I'm getting a 401 error when using your token:

    Failed to load resource: the server responded with a status of 401 (Unauthorized)

    When i use your code with Mapbox's example token and map (note, you should be using your own token and map) it's perfectly fine:

    L.mapbox.accessToken = 'pk.eyJ1IjoicGF1bC12ZXJob2V2ZW4iLCJhIjoiZ1BtMWhPSSJ9.wQGnLyl1DiuIQuS0U_PtiQ';
    
    var map = L.mapbox.map('mapbox', 'examples.map-i86nkdio', {
        'center': [0, 0],
        'zoom': 1
    });
    

    Working example on Plunker: http://plnkr.co/edit/wrlC7AAHLBWsDgzk8PRw?p=preview

    I'de double check your accounttoken and map id.