首页 > 解决方案 > 如何将条件放在地图功能中

问题描述

我正在使用 geolib 来获取点在圆圈内,下面的函数只返回 TRUE/FALSE。

geolib.isPointWithinRadius(
    { latitude: 51.525, longitude: 7.4575 }, // My current location.
    { latitude: 51.5175, longitude: 7.4678 }, // returns TRUE if this point is within 5 km radius from my current location.
    5000
);

是的,它正在工作。但我想要的是,我想检查多个位置。例如,我有以下数组,我想检查相同的函数来检查所有位置,如果任何一个位置在我的位置 5 公里内,它应该返回 TRUE。换句话说,只有当所有位置都不在我当前位置的 5 公里范围内时,我才会得到 FALSE

const markers = [
    {
      title: "my location1",
      coordinates: {
        latitude: 14.599912,
        longitude: 24.1147557,
      },
    },
    {
      title: "my location 2",
      coordinates: {
        latitude: 34.599912,
        longitude: 44.1147557,
      },
    },
    {
      title: "my location 3",
      coordinates: {
     latitude: 54.599912,
        longitude: 64.1147557,
      },
    },
  ];

我试过这个,

geolib.isPointWithinRadius(
    { latitude: 51.525, longitude: 7.4575 },
    markers.map((marker) => marker.coordinates),
    50
  );

我得到的只是假的,我真的很感谢你的帮助。提前致谢。

标签: javascriptreact-native

解决方案


some方法可用于检查是否至少一项返回 true:

const isWithinRange = markers.some(marker => {
  return geolib.isPointWithinRadius(
    { latitude: 51.525, longitude: 7.4575 },
    marker.coordinates,
    50
  );
})

文档:https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some


推荐阅读