• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

182
Views
Leaflet.js wrap LatLng positions of line to nearest line

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?

about 3 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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);

}
about 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error