In the last post I described how to create a map with markers on it. I'm going to build on this to make some improvements. Firstly, the default markers are useful but it would be good to have some alternatives. I copied the example1.htm, .js and .css files to example2.x and made some changes there. I created three images which are blue, green and white disks and saved them in the images folder. To use these images we need to create a Leaflet Icon for each marker type. The variables used to store the Icon objects are declared in the global area and then the Icon is created before anything else is created so it is available whenever we need it.
blueicon=L.icon({
iconUrl: 'images/blueplaque.png',
iconSize:[24, 24], // size of the icon
iconAnchor:[12, 23] // point of the icon which will correspond to marker's location
});
greenicon=L.icon({
iconUrl: 'images/greenplaque.png',
iconSize:[24, 24], // size of the icon
iconAnchor:[12, 23] // point of the icon which will correspond to marker's location
});
whiteicon=L.icon({
iconUrl: 'images/whiteplaque.png',
iconSize: [24, 24], // size of the icon
iconAnchor:[12, 23] // point of the icon which will correspond to marker's location
});
The icons use the images from the images folder. The icon anchor is important to make a marker work well especially when zooming. If your marker seems to slide around as you zoom in or out you probably don't have the anchor set correctly. It defaults to [0,0] which is top left and rarely what you want.
In the last example we used events to add popups to each markers, here we want to substitute the markers, so we need to change the behaviour, but not much. When we create the geojson layer we need to remove the onEachFeature and replace it with pointToLayer:
lyrPlq = L.geoJson(plaques, {
pointToLayer: setIcon
}
);
The pointToLayer event allows you to provide the marker you want to display for each feature. The function you define, setIcon in this case, gets passed the feature and the position that the marker need to be as a leaflet LngLat object. In the function you create a marker or some other Leaflet object and return that. Leaflet adds what you return to the layer.
function setIcon(feature,ll) {
var plq;
if (feature.properties.colour=='green') {
plq=L.marker(ll, {icon: greenicon});
}
else if (feature.properties.colour=='white') {
plq=L.marker(ll, {icon: whiteicon});
}
else {
plq=L.marker(ll, {icon: blueicon});
}
plq.bindPopup(feature.properties.plaquedesc);
return p;
}
In this case we use one of the properties, colour, to choose the marker to display. We now need to add the popup to our newly created marker and return the marker for Leaflet to use.
You can see an example here. The source code is on GitHub.
More examples to come ...
No comments:
Post a Comment