How to add a floating "crosshairs" icon above leaflet map?
It makes use of the Leaflet function getCenter()
. The function returns the geographical center of the map view.
BBoxfinder has the same thing. Looking into the source code I found the following:
// Add in a crosshair for the map
var crosshairIcon = L.icon({
iconUrl: 'images/crosshair.png',
iconSize: [20, 20], // size of the icon
iconAnchor: [10, 10], // point of the icon which will correspond to marker's location
});
crosshair = new L.marker(map.getCenter(), {icon: crosshairIcon, clickable:false});
crosshair.addTo(map);
// Move the crosshair to the center of the map when the user pans
map.on('move', function(e) {
crosshair.setLatLng(map.getCenter());
});
The coordinates are added to the HTML with jQuery:
$('#center').text(formatPoint(map.getCenter(),'4326'));
You can also float a crosshair image or character over your map using HTML and CSS. I'm using a plus sign in this example but you can swap that out for an image.
calc(50% - 10px) works out to be 1/2 of the map div, minus 1/2 of the crosshair div.
CSS:
#crosshair {
left: calc(50% - 10px);
top: calc(50% - 10px);
position: absolute;
width: 20px;
height: 20px;
z-index: 10000;
text-align: center;
font-weight: normal;
font-size: 16px;
color: #222;
text-shadow: 1px 1px 3px #fff;
}
HTML:
<div id="map">
<div id='crosshair'>+</div>
</div>