N
N
Nik17122016-11-30 16:37:17
JavaScript
Nik1712, 2016-11-30 16:37:17

How to sort objects by distance, knowing the coordinates in JS?

There is a definition of the current location of the user. You need to make a filter to display objects by distance, starting from the closest to the farthest. To do this, as I understand it, you need to display them in ascending order of distance from smaller to larger. How to find out these distances if the coordinates of each object are known (they will be, say, in the data attributes of the objects) in JS?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Dmitry Eremin, 2016-11-30
@EreminD

Geometry. Some kind of class
1. In fact, we have a bunch of vectors.
2. They all start at one point (current). For convenience, keep it as (0, 0)
3. The coordinates of your points are the ends of the vectors
4. Calculate the length of each vector

//тут массив с вашими объектами
var items = [ {x: 1, y: 1}, 
      { x: 22, y: 0}, 
      { x: 2, y: 0},
      { x: 0, y: 1},
      { x: 2, y: 2},
      { x: 1, y: 2},
      ]

//тут будут храниться пары {объект, удаленность}
var sorteditems = [];

//получаем для каждого удаленность
items.forEach(getLength);
//сортируем по удаленности. сначала самые ближние. Если поставить {return b.len - a.len;}, то будут сначала самые дальние
var res = sorteditems.sort(function compare(a, b){return a.len - b.len;}); 
//фсе
console.log(res);


//вот тут описано, как получаем для каждого удаленность
function getLength(item, index, array) {
  var len = Math.sqrt(Math.pow(item.x, 2) + Math.pow(item.y, 2));
  sorteditems.push({item, len});
}

UPD: to consider the current position as (0; 0) is incorrect, since the coordinates of objects do not start relative to the user, but relative to the general zero.
So the correct distance calculation is as follows:
1. Get the geolocation of the smartphone X and Y
2. For each of your objects on the map, we find the vector: AB = {item.x - X; item.y - Y}.
3. And then we only calculate the length of the vector AB (as described above)

G
GreatRash, 2016-11-30
@GreatRash

var point_1 = {
  x: 10,
  y: 20
};

var point_2 = {
  x: 17,
  y: 3
};

var vector = {
  x: point_1.x - point_2.x,
  y: point_1.y - point_2.y
};

var vecror_length = Math.sqrt(vector.x * vector.x + vector.y * vector.y);
var distance = vector_length;

D
Denis, 2016-11-30
@Deonisius

Script (look at the bottom of the page) and an article describing sorting example.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question