Изучение поиска радиуса Geopoint в Mongoose: подробное руководство

Геопространственные запросы – это мощная функция, предлагаемая MongoDB и поддерживаемая Mongoose, популярной библиотекой моделирования объектных данных (ODM) для Node.js. В этой статье мы рассмотрим различные методы поиска геоточек в заданном радиусе с помощью Mongoose. Мы рассмотрим примеры кода для каждого метода, что позволит вам реализовать поиск по радиусу геоточки в ваших собственных проектах.

Метод 1. Использование оператора $near:
Оператор $near в Mongoose позволяет находить геоточки в пределах заданного радиуса от заданной точки. Вот пример того, как его использовать:

const geoPointSchema = new mongoose.Schema({
  location: {
    type: { type: String, enum: ['Point'], required: true },
    coordinates: { type: [Number], required: true }
  }
});
geoPointSchema.index({ location: '2dsphere' });
const GeoPoint = mongoose.model('GeoPoint', geoPointSchema);
const centerPoint = {
  type: 'Point',
  coordinates: [longitude, latitude] // Specify the center point coordinates
};
const radiusInMeters = 1000; // Define the radius in meters
GeoPoint.find({
  location: {
    $near: {
      $geometry: centerPoint,
      $maxDistance: radiusInMeters
    }
  }
})
  .then(geopoints => {
    // Handle the found geopoints
  })
  .catch(err => {
    // Handle any errors
  });

Метод 2. Использование оператора $geoWithin:
Оператор $geoWithin позволяет находить геоточки в пределах указанного радиуса с помощью многоугольника GeoJSON. Вот пример:

const radiusInMeters = 1000; // Define the radius in meters
const polygon = {
  type: 'Polygon',
  coordinates: [[
    // Define the coordinates of a square polygon
    [longitude - radiusInMeters / 111320, latitude - radiusInMeters / 111320],
    [longitude + radiusInMeters / 111320, latitude - radiusInMeters / 111320],
    [longitude + radiusInMeters / 111320, latitude + radiusInMeters / 111320],
    [longitude - radiusInMeters / 111320, latitude + radiusInMeters / 111320],
    [longitude - radiusInMeters / 111320, latitude - radiusInMeters / 111320]
  ]]
};
GeoPoint.find({
  location: {
    $geoWithin: {
      $geometry: polygon
    }
  }
})
  .then(geopoints => {
    // Handle the found geopoints
  })
  .catch(err => {
    // Handle any errors
  });

Метод 3. Использование круга GeoJSON.
В этом методе мы создаем круг GeoJSON и используем оператор $geoWithin для поиска геоточек внутри круга. Вот пример:

const radiusInMeters = 1000; // Define the radius in meters
const circle = {
  type: 'Feature',
  geometry: {
    type: 'Point',
    coordinates: [longitude, latitude] // Specify the center point coordinates
  },
  properties: {
    radius: radiusInMeters
  }
};
GeoPoint.find({
  location: {
    $geoWithin: {
      $geometry: circle
    }
  }
})
  .then(geopoints => {
    // Handle the found geopoints
  })
  .catch(err => {
    // Handle any errors
  });

В этой статье мы рассмотрели три метода поиска геоточек в пределах заданного радиуса с помощью Mongoose. Используя методы $near, $geoWithin и GeoJSON, вы можете реализовать мощные возможности геопространственных запросов в своих проектах Node.js и MongoDB. Имея в своем распоряжении эти методы, вы можете легко находить геоточки по их близости к заданной точке. Приятного кодирования!