mongodb & google 地图 - 获取半径范围内的位置且不准确

mongodb & google maps - get locations on radius without inaccuracy

我在 mongodb 中存储了位置,在 mongoose 架构中看起来像这样:

location: {
    type: [Number],
    index: '2d'
}

在 Web 客户端上,我使用 google 地图 api 和自定义半径调整器:

在每次拖动时,我都使用在客户端计算的半径值发出请求。 Radius是粉色箭头标记到中心坐标的距离:

function metersToMiles (meters) {
    return meters * 0.000621371192;
}

google.maps.event.addListener(this.sizer, 'dragend', () => {
    const radius = this.circle.getRadius();
    const radiusValue = Math.round(metersToMiles(radius) * 10) / 10; // convert to tenths (this is shown on UI as well)
    this.props.onRadiusChange(radiusValue); // it's a react component
});

在 mongodb 请求中我使用 $nearSphere 半径在 $maxDistance:

function milesToRadian(miles){
   const earthRadiusInMiles = 3963.2;
   return parseFloat(miles) / earthRadiusInMiles;
}
const { radius, lat, lon } = req.query;
const coords = (lat && lon) ? [lat, lon] : ukCoordinates;
const radians = milesToRadian(radius);
console.log('%s, %s, %s', radius, coords, radians);
// what I receive: 1.6, 0.00040371417036737993, [ 51.507351, -0.127758 ]

// ...
{
   $nearSphere: coords,
   $maxDistance: radians
}

但是,如果您查看 gif 图像,您会发现结果有些不准确。现在我坚持了下来,你能告诉我问题出在哪里吗?

所以这个问题真的很有趣但仍然很棘手。我发现在 MongoDB 中你需要将坐标对存储为 [longitude, latitude] 而不是相反:

location: {
   type: [Number], // longitude, latitude
   index: '2d'
}

但在 Google Maps SDK 中顺序不同:

new google.maps.LatLng(lat, lng);

因此,为了解决我的问题,我需要以正确的顺序在 MongoDB 中存储坐标。