js实现附近商家
实现附近商家功能的方法
获取用户地理位置
使用浏览器提供的Geolocation API获取用户的经纬度坐标。代码示例如下:
navigator.geolocation.getCurrentPosition(
(position) => {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
console.log(`Latitude: ${latitude}, Longitude: ${longitude}`);
},
(error) => {
console.error("Error getting location:", error.message);
}
);
计算距离
使用Haversine公式计算两个经纬度坐标之间的距离(单位:公里)。公式实现如下:

function calculateDistance(lat1, lon1, lat2, lon2) {
const R = 6371; // 地球半径,单位公里
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 filterNearbyShops(userLat, userLng, shops, radiusKm) {
return shops.filter(shop => {
const distance = calculateDistance(
userLat, userLng,
shop.location.lat, shop.location.lng
);
return distance <= radiusKm;
});
}
地图展示集成
使用地图API(如Google Maps或高德地图)展示附近商家:
// 使用Google Maps API示例
function initMap() {
const map = new google.maps.Map(document.getElementById("map"), {
center: {lat: userLat, lng: userLng},
zoom: 15
});
// 添加用户位置标记
new google.maps.Marker({
position: {lat: userLat, lng: userLng},
map: map,
title: "您的位置"
});
// 添加附近商家标记
nearbyShops.forEach(shop => {
new google.maps.Marker({
position: {lat: shop.location.lat, lng: shop.location.lng},
map: map,
title: shop.name
});
});
}
性能优化建议
对于大量商家数据,考虑使用空间索引技术如R-tree或GeoHash来加速距离计算。可以使用现成的库如Turf.js或geolib来处理地理空间计算。
注意事项
- 需要处理用户拒绝地理位置权限的情况
- 移动端建议使用watchPosition实时更新位置
- 隐私政策中需说明位置数据的使用方式
- 考虑添加距离排序和筛选功能提升用户体验
以上方法组合使用即可实现一个完整的附近商家功能,包括位置获取、距离计算、数据筛选和地图展示。


