algorithmgeographic-distance

Algorithm to regroup geographic points


I'm creating an app using a map and I have to place points on it. The problem is that when the points are nearby, the user can't see the difference. So, I need to regroup the points.

I receive JSONs like that:

[{"id": "1", "x": 253, "y": 144}, 
{"id": "2", "x": 142, "y": 355}, 
{"id": "3", "x": 175, "y": 330}, 
{"id": "4", "x": 140, "y": 5}, 
{"id": "5", "x": 307, "y": 306}, 
{"id": "6", "x": 233, "y": 304}, 
{"id": "7", "x": 212, "y": 163}, 
{"id": "8", "x": 202, "y": 163}, 
{"id": "9", "x": 204, "y": 171}]

And i need to regroup point with 20px difference in biggest point with coord of the average of all other points. It's deal a JSON like that:

[{"id": ["1"], "x": 253, "y": 144}, 
{"id": ["2"], "x": 142, "y": 355}, 
{"id": ["3"], "x": 175, "y": 330}, 
{"id": ["4"], "x": 140, "y": 5}, 
{"id": ["5"], "x": 307, "y": 306}, 
{"id": ["6"], "x": 233, "y": 304}, 
{"id": ["7","8","9"], "x": 206, "y": 165}]

I just need an algorithm to help me to build my own code.

Thank you for all help you can give to me.


Solution

  • Euclidian distance is the shortest path between two points and calculated as

    sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2))
    

    Just iterate through your list of points from the top to the bottom and if the Euclidean distance between any two points is less than 20, remove the second point or group it with the first one, so you won't have to process it again. You can then calculate the average location of that group if you want to.