Skip to content

Instantly share code, notes, and snippets.

@geog4046instructor
Last active June 8, 2022 15:08
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save geog4046instructor/80ee78db60862ede74eacba220809b64 to your computer and use it in GitHub Desktop.
Save geog4046instructor/80ee78db60862ede74eacba220809b64 to your computer and use it in GitHub Desktop.
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
Copy link

xg590 commented Aug 23, 2019

Thx for you example. It works fine!

@hiongyi
Copy link

hiongyi commented Nov 30, 2019

thx!!! It works!!

@Shadrock
Copy link

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