MapBox: HTML markers with GeoJson layers

(This is an auto copy over from my old blog at Joe8bit.com, some links may be broken)

Using HTML markers with rendering GeoJSON layers

I’m a big fan of MapBox, I use it wherever I can when I need maps (CartCSS + TileMill is a ray of sunshine in the otherwise crappy world of custom maps).

One of the main reasons I love their service so much is the quality of their documentation, which rarely fails to present an answer to a question I’ve had, until this instance.

So in the interest in saving a few minutes of pissing about, below is my solution to using custom HTML markers when rendering GeoJSON layers with Mapbox.js.

// Create your map is you normally would
L.mapbox.accessToken = 'YOUR_TOKEN';
var map = L.mapbox.map('map', 'YOUR_MAP').setView([YOUR_LAT, YOUR_LONG], YOUR_ZOOM);

// Add a layer with no data set as the first arg to featureLayer()// This is done to prevent the default marker icons rendering
var layer = L.mapbox.featureLayer().addTo(map);

// When the 'layeradd' event is fired (when we add the geoJSON below)layer.on('layeradd', function (e) {
var marker = e.layer;
var feature = marker.feature;

// This is where the magic happens...
marker.setIcon(L.divIcon({
    className: YOUR_ICON_CLASS, // Make sure you set an icon class here, otherwise default styles will be set by Mapbox's CSS
    html: '
<h1>Hello World</h1>
', // The content of your HTML marker, you can build a string based on the marker properties by using 'feature.properties.your_property'
    iconSize: [60,60] // The bounds for your icon
}));

// Now set your data and render the maplayer.setGeoJSON(YOUR_GEOJSON_DATA);

I can’t say for sure this is the best way to do it, but it works nicely and performantly for me.

Advertisements