Js实现附近订单
实现附近订单功能的方法
获取用户位置
使用浏览器提供的Geolocation API获取用户的当前位置坐标。代码示例如下:
navigator.geolocation.getCurrentPosition(
(position) => {
const { latitude, longitude } = position.coords;
console.log(latitude, longitude);
},
(error) => {
console.error(error);
}
);
存储订单位置数据
订单数据需要包含经纬度信息。数据库结构可以设计为:
{
orderId: "123",
location: {
lat: 39.9042,
lng: 116.4074
},
// 其他订单信息
}
计算距离
使用Haversine公式计算两点之间的距离(单位:公里):
function calculateDistance(lat1, lon1, lat2, lon2) {
const R = 6371; // 地球半径(km)
const dLat = (lat2 - lat1) * Math.PI / 180;
const dLon = (lon2 - lon1) * Math.PI / 180;
const a =
Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(lat1 * Math.PI / 180) *
Math.cos(lat2 * Math.PI / 180) *
Math.sin(dLon/2) * Math.sin(dLon/2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
return R * c;
}
筛选附近订单
获取用户位置后,筛选指定半径范围内的订单:
function getNearbyOrders(userLat, userLng, orders, radiusKm) {
return orders.filter(order => {
const distance = calculateDistance(
userLat,
userLng,
order.location.lat,
order.location.lng
);
return distance <= radiusKm;
});
}
优化性能
对于大量订单数据,可以考虑以下优化:
- 使用空间索引(如GeoHash)
- 在数据库层面进行地理位置查询(MongoDB有$near操作符,MySQL有空间函数)
- 实现分页加载避免一次性处理过多数据
前端展示
在地图上标记附近订单位置,可以使用地图API如Google Maps或Mapbox:
// 使用Mapbox示例
mapboxgl.accessToken = 'YOUR_ACCESS_TOKEN';
const map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v11',
center: [userLng, userLat],
zoom: 12
});
nearbyOrders.forEach(order => {
new mapboxgl.Marker()
.setLngLat([order.location.lng, order.location.lat])
.addTo(map);
});






