5

While reading the article about MapBox's map utility to searching for flight MH370, I noticed that they have a stationary "floating" target (or crosshairs) icon that helps users identify the center of the map, presumably to help them get the exact coordinates they are intending to report.

I've searched our site, but cannot find anything that relates to how to create this object that (I assume) just sits above the map frame.

How would one add a target (or crosshairs) icon centered on their own Leaflet map?

10

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'));
  • Thanks, this was perfect! I spent so long in trying to position an external diff, wish I'd found this earlier. Note : clickable is now interactive – Nikhil VJ May 17 at 2:14
0

This thread might help even if it is in GoogleAPI, the idea is essentially the same I believe. Set marker position to map.getCenter() then map.on('move', updateMarker(map.getCenter())?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.