I want to have the user click two positions and then draw a line between them. This is totally functional and easy. And it also works if the click is outside the -180;180 range.
createPolyLine(outside2, userLocation);
//draw polyline
function createPolyLine(loc1, loc2) {
var latlongs = [loc1, loc2];
console.log(loc1);
var polyline = new L.Polyline(latlongs, {
color: 'white',
opacity: 1,
weight: 1,
clickable: false
}).addTo(map);
}
Now If a user clicks say on longitude of -600 I want to have it automatically wrap into the -180;180 area but only if its the closest path. If its closer to keep the click in the -360:-180 area then it should wrap into the -360;-180 area. Same for the other side in positive direction ofcourse. Example image of what i mean:
Example of when its closer to use -360;-180 region and not wrap it into -180;180
Example of when its closer to use -180;180 and it would be wrong now
Based on second example but correctly wrapped now
What would be the most efficient way to achieve this auto wrap into either -360;-180 / -180;180 / 180;360 depending on where the closest line between two points would be?
Thanks to the response of Corey Alix I came up with a solution which feels kinda dirty but it works for all the test cases I tried against. In my scenario one point is always in -180;180 range.
// a is always in -180;180
function getPositions(a, b) {
b.lng %= 360;
let abs = Math.abs(a.lng - b.lng);
let absWrap = Math.abs(a.lng - b.wrap().lng);
if(absWrap < abs) {
b = b.wrap();
abs = absWrap;
}
let left = new L.LatLng(b.lat, b.lng - 360);
let right = new L.LatLng(b.lat, b.lng + 360);
let leftAbs = Math.abs(a.lng - left.lng);
if(leftAbs < abs) {
b = left;
abs = leftAbs;
}
if(Math.abs(a.lng - right.lng) < abs) {
b = right;
}
return [a, b];
}
//draw polyline
function createPolyLine(loc1, loc2) {
var latlongs = getPositions(loc2, loc1);
polyline = new L.Polyline(latlongs, {
color: 'white',
opacity: 1,
weight: 1,
clickable: false
}).addTo(map);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.