Adding custom icon marker using mapbox js

Custom markers can be used to replace the default markers in a mapbox project.  A custom icon marker  can improve the looks of the map and better renders the information the map is designed to pass on to the end user. This simple demonstration below will add a custom marker into a mapbox project using the mapbox javascript api.

 

We create a feature layergroup of geojson point features and insert it within the script.
 // A layer (Points) made up of the geojson point features is created and added to the base map

var Points = L.mapbox.featureLayer().addTo(map);

 

// create the geojson point features. Under “properties”, add “icon”: and define the location

, size, anchor, popupAnchor and className for the custom icon.

var cities = [{
“type”: “Feature”,
“geometry”: {
“type”: “Point”,
“coordinates”: [38.75, 9.02]
},
“properties”: {
“title”: “addis-ababa”,
“icon”: {
“iconUrl”: “https://lh3.googleusercontent.com/xnJpBEZx1d09ykDdj9G6_cM_C5E7-KfCbIL2B1iOkg=s64-no”,
“iconSize”: [35, 35], // size of the icon
“iconAnchor”: [50, 50], // point of the icon which will correspond to marker’s location
“popupAnchor”: [0, -25], // point from which the popup should open relative to the iconAnchor
“className”: “dot”
}
}
}, {
“type”: “Feature”,
“geometry”: {
“type”: “Point”,
“coordinates”: [8.00, 9.00]
},
“properties”: {
“title”: “abuja”,
“icon”: {
“iconUrl”: “https://lh3.googleusercontent.com/BXBeG-J7SB7MAkLXch96W-8vQvJ09cmXlH1eB1XDIo0=w119-h109-no”,
“iconSize”: [20, 20],
“iconAnchor”: [20, 20],
“popupAnchor”: [0, -55],
“className”: “dot”
}
}
}];


Designate a custom icon for each feature

Points.on(‘layeradd’, function(e) {
var marker = e.layer,
feature = marker.feature;

marker.setIcon(L.icon(feature.properties.icon));
});

 

Finally, add the geojson point features to the base map

 

Points.setGeoJSON(cities);


Below is a screenshot of the web page containing the mapbox base layer

with the custom icons displayed on the base map.

Capture-1

 

See live map at:

http://htmlpreview.github.io/?https://github.com/mayotunde/webmap/blob/gh-pages/customiconsmapbox

 

Download plain text version of the source code at:

https://www.dropbox.com/s/yfyyotq1i0xwdyk/Adding%20custom%20icons%20using%20mapbox%20js.txt?dl=0

 

Below is the source code:

dim-001

 

Thank you for following the demonstration.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s