Skip to content

Instantly share code, notes, and snippets.

@neatstudio
Created July 7, 2021 02:48
Show Gist options
  • Save neatstudio/3d3b8e728e06432eb0141c6b602c0a37 to your computer and use it in GitHub Desktop.
Save neatstudio/3d3b8e728e06432eb0141c6b602c0a37 to your computer and use it in GitHub Desktop.
简单的JS来判断距离
let items = [
{
id: "3",
name: "XXX",
address: "BBBB",
lon: 114.1654,
lat: 22.27534,
},
{
id: "2",
name: "YYYY",
address: "AAA",
lon: 121.4369,
lat: 31.1883,
},
{
id: "7",
name: "菠萝酥",
address: "虹梅路1905",
lon: 121.4846,
lat: 31.2316,
},
{
id: "1",
name: "ZZZZ",
address: "CCC",
lon: 121.3934,
lat: 31.1592,
},
{
id: "4",
name: "UUU",
address: "DDDD",
lon: 121.4208,
lat: 31.1712,
},
{
id: "6",
name: "VVVV",
address: "EEEE",
lon: 121.4801,
lat: 31.236,
},
{
id: "5",
name: "WWWWW",
address: "FFFFFF",
lon: 121.4452,
lat: 31.2245,
},
];
let user = [31.24, 121.24];
function distance(lat1, lng1, lat2, lng2) {
var radLat1 = (lat1 * Math.PI) / 180.0;
var radLat2 = (lat2 * Math.PI) / 180.0;
var a = radLat1 - radLat2;
var b = (lng1 * Math.PI) / 180.0 - (lng2 * Math.PI) / 180.0;
var s =
2 *
Math.asin(
Math.sqrt(
Math.pow(Math.sin(a / 2), 2) +
Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)
)
);
return Math.round(s * 6378.137 * 1000) / 1000;
}
items.forEach((item) => {
item.distance = distance(user[0], user[1], item.lat, item.lon);
});
let t = items.sort((a, b) => {
return a.distance - b.distance;
});
t.map((item) => {
let dis =
item.distance < 10 ? item.distance * 1000 + " 米" : item.distance + "公里";
console.log(`name:${item.name} => 距离:${dis}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment