mongodb和谷歌地图 – 获取半径没有不准确的地点
我在mongodb模式下存储了如下所示的位置:
location: { type: [Number], index: '2d' }
而在networking客户端,我使用谷歌地图API与自定义半径resize:
在每次拖动我正在请求与客户端上计算的半径值。 半径是粉红色箭头标记和中心坐标之间的距离:
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请求中,我在$maxDistance
使用半径$maxDistance
$nearSphere
:
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地图SDK中,顺序是不同的:
new google.maps.LatLng(lat, lng);
所以要解决我的问题,我需要在MongoDB中以正确的顺序存储坐标。