3

I just started playing with MapBox and am running into a confusing issue. I'm creating a map with a geoJSON layer using this code:

var map = L.mapbox.map('map', '<MapBoxID>');
            var zipLayer = L.mapbox.featureLayer('data/blah.json');
            zipLayer.addTo(map);
            zipLayer.setStyle({color: 'red'});

The map appears and shows the geoJSON, but it ignores the styling. When I copy that last line into the JS console in my browser, it works fine, though.

What am I missing here? Also, I've tried at least a dozen different ways of including the style in the options directly in the featureLayer() call, but nothing has worked. How do I specify the style when creating the feature layer?

3 Answers 3

4

I'm guessing a bit here, since I don't know the Mapbox JS very well, but it sounds a lot like an async error. Strangely, I don't see anything in the Mapbox or Leaflet APIs about a callback for this function. But, you can pass straight GeoJSON to featureLayer(), so I'd suggest using jQuery (or your XHR library of choice) to grab the data:

var map = L.mapbox.map('map', '<MapBoxID>');
var zipLayer;

$.getJSON('data/blah.json', function(data) {
    zipLayer = L.mapbox.featureLayer(data);
    zipLayer.addTo(map);
    zipLayer.setStyle({color: 'red'});
});

Hopefully that'll do the trick.

1
  • Thanks, that works! Still confused what's going on here, though. Perhaps there is a better solution still. Commented Apr 26, 2014 at 1:06
3

I would go the route of using the built-in featureLayer function, then listening for it to be ready. This should help get you pointed in the right direction:

var featureLayer = L.mapbox.featureLayer()
    .loadURL('/example-single.geojson')
    .on('ready', function(layer) {
        this.eachLayer(function(marker) {
            // See the following for styling hints:
            // https://help.github.com/articles/mapping-geojson-files-on-github#styling-features
            marker.setIcon(L.mapbox.marker.icon({
                'marker-color': '#CC0000'
            }));
        });
    })
    .addTo(map);
1
  • Thanks! I figured I could just set style parameters at any time. It seems odd that I have to wait for the layer to be loaded to do that. I also lose the styling when I load other geoJSON, which is unexpected. Anyway, thanks! Commented Apr 26, 2014 at 23:50
1

Have you tried adding the zipLayer after setting the style?

1
  • 1
    Good question: yes, just did. Doesn't work either. I must be doing something wrong, I'm just not seeing what. Commented Apr 26, 2014 at 0:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.