Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Leaflet - Create a custom icon to use with a GeoJSON layer instead of the default blue marker
/*
* Create a custom icon to use with a GeoJSON layer instead of the default blue
* marker. This snippet assumes the map object (map) and GeoJSON object
* (myLayerData) have already been declared.
*/
// replace Leaflet's default blue marker with a custom icon
function createCustomIcon (feature, latlng) {
let myIcon = L.icon({
iconUrl: 'my-icon.png',
shadowUrl: 'my-icon.png',
iconSize: [25, 25], // width and height of the image in pixels
shadowSize: [35, 20], // width, height of optional shadow image
iconAnchor: [12, 12], // point of the icon which will correspond to marker's location
shadowAnchor: [12, 6], // anchor point of the shadow. should be offset
popupAnchor: [0, 0] // point from which the popup should open relative to the iconAnchor
})
return L.marker(latlng, { icon: myIcon })
}
// create an options object that specifies which function will called on each feature
let myLayerOptions = {
pointToLayer: createCustomIcon
}
// create the GeoJSON layer
L.geoJSON(myLayerData, myLayerOptions).addTo(map)
@xg590

This comment has been minimized.

Copy link

@xg590 xg590 commented Aug 23, 2019

Thx for you example. It works fine!

@hiongyi

This comment has been minimized.

Copy link

@hiongyi hiongyi commented Nov 30, 2019

thx!!! It works!!

@Shadrock

This comment has been minimized.

Copy link

@Shadrock Shadrock commented Oct 12, 2020

Great example: one of my students found this and found it very useful! Thanks for posting.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment