I have written some code which creates a rectangle at the position of the user's cursor. There does not seem to be any method to do this in turf.js itself. And of course using the latlong-based coordinates of leaflet, it becomes difficult to do so since it requires mixing geographic & projected coordinates.
But I still have to do this. Ignoring effects from extreme polar distortion (the map will not allow the user to zoom out far enough, nor allow them to pan to regions where these effects will become significant), this is the method I have come up with. In broad strokes:
- Get the latlng of the cursor (via a
mousemoveevent listener on the map). - Use the
destinationmethod to "throw" a point in all four cardinal directions to get points which represent the left, right, upper and lower limits. - Calculate a rectangle using the
envelopemethod
Is there a simpler way of doing this? It seems like it is rather roundabout
This is the code. Obviously it could be made more compact but I have left it stretched out across multiple var declarations for the sake of readability.
var offsetX = $("#rectangle-width-input").val()/2; // User input for rectangle width
var offsetY = $("#rectangle-height-input").val()/2; // User input for rectable height
var topLimit = turf.destination(
[ev.latlng.lng, ev.latlng.lat] // Mouse cursor location (in latlng),
offsetY,
0,
{"units": "meters"})
var rightLimit = turf.destination(
[ev.latlng.lng, ev.latlng.lat] // Mouse cursor location (in latlng),
offsetX,
90,
{"units": "meters"})
var bottomLimit = turf.destination(
[ev.latlng.lng, ev.latlng.lat] // Mouse cursor location (in latlng),
offsetY,
180,
{"units": "meters"})
var leftLimit = turf.destination(
[ev.latlng.lng, ev.latlng.lat] // Mouse cursor location (in latlng),
offsetX,
-90,
{"units": "meters"})
mouseShape = turf.envelope(turf.featureCollection([ // Resultant rectangle
topLimit,
rightLimit,
bottomLimit,
leftLimit
]));