本文档旨在指导开发者如何使用Leaflet地图库,结合JSON格式的自行车站点数据,计算给定坐标点与各个站点之间的距离,并找出最近的站点。我们将提供JavaScript代码示例,详细解释距离计算方法,以及如何在Leaflet地图上应用这些数据,最终实现查找最近站点的功能。
### 1. 准备工作
首先,确保你已经引入了Leaflet库及其相关的依赖。 在HTML文件中添加以下代码:
“`html
<link rel=”stylesheet” href=”https://unpkg.com/leaflet@1.7.1/dist/leaflet.css” />
<script src=”https://unpkg.com/leaflet@1.7.1/dist/leaflet.js”></script>
<script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js”></script>
<script src=”https://cdnjs.cloudflare.com/ajax/libs/leaflet-routing-machine/3.2.12/leaflet-routing-machine.min.js”></script>
同时,确保你有一个包含自行车站点信息的json文件(例如 citybike.json),其结构类似于以下示例:
{ "stationBeanList": [ { "id": 72, "stationName": "W 52 St & 11 Ave", "availableDocks": 32, "totalDocks": 39, "latitude": 40.76727216, "longitude": -73.99392888, "statusValue": "In Service", "statusKey": 1, "availableBikes": 6, "stAddress1": "W 52 St & 11 Ave", "stAddress2": "", "city": "", "postalCode": "", "location": "", "altitude": "", "testStation": false, "lastCommunicationTime": null, "landMark": "" }, { "id": 76, "stationName": "1st & Houston", "availableDocks": 23, "totalDocks": 30, "latitude": 41.76727216, "longitude": -74.99392888, "availableBikes": 7 }, { "id": 12, "stationName": "White plains", "availableDocks": 12, "totalDocks": 22, "latitude": 51.76727216, "longitude": 1.99392888, "availableBikes": 10 } ] }
2. 计算距离的函数
我们将使用Haversine公式来计算两个坐标点之间的距离。以下是一个JavaScript函数,用于计算地球上两点之间的距离(以米为单位):
function getDistance(lat1, lon1, lat2, lon2, unit = 'M') { const R = 6371e3; // 地球半径(米) const φ1 = lat1 * Math.PI/180; const φ2 = lat2 * Math.PI/180; const Δφ = (lat2-lat1) * Math.PI/180; const Δλ = (lon2-lon1) * Math.PI/180; const a = Math.sin(Δφ/2) * Math.sin(Δφ/2) + Math.cos(φ1) * Math.cos(φ2) * Math.sin(Δλ/2) * Math.sin(Δλ/2); const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); const d = R * c; // 距离(米) if (unit === 'km') return d * 0.001; if (unit === 'mi') return d * 0.0006213712; return d; }
这个函数接受两个坐标点的纬度和经度,以及一个可选的单位参数(默认为米)。 你也可以选择返回公里或英里。
3. 查找最近站点的函数
接下来,创建一个函数,该函数接受起始坐标、站点列表和单位,并返回按距离排序的站点列表:
function getStationDistances(locLat, locLng, stationsList, unit = 'mi') { return stationsList.map(station => { const { id, stationName: name, latitude: sLat, longitude: sLng, availableDocks } = station; const distance = Number.parseFloat((Math.round(getDistance( locLat, locLng, sLat, sLng, unit) * 100) / 100).toFixed(2)); return { id, name, distance, unit, sLat, sLng, availableDocks }; }).sort((a, b) => a.distance > b.distance); }
这个函数使用 map 方法遍历站点列表,计算每个站点与给定坐标之间的距离,并将结果存储在一个新的对象中。 然后,使用 sort 方法按距离对结果进行排序。
4. 在Leaflet地图上应用
现在,让我们将这些函数应用到Leaflet地图上。 首先,创建一个地图实例:

在线工具导航网站,免费使用无需注册,快速使用无门槛。

查看详情
var map_var = L.map('map_id').setView([40.72730240765651, -73.9939667324035], 16); L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors' }).addTo(map_var); var startPosition = L.latLng(); var endPosition = L.latLng(); L.Routing.control({ waypoints: [ startPosition, endPosition, ], routeWhileDragging: true, collapsible: true, geocoder: L.Control.Geocoder.nominatim() }).addTo(map_var);
然后,使用 $.getJSON 方法加载JSON数据,并调用 getStationDistances 函数来查找最近的站点:
$.getJSON("citybike.json", function (json1) { const locationLat = 40.72730240765651; // 起始纬度 const locationLng = -73.9939667324035; // 起始经度 const nearestStations = getStationDistances(locationLat, locationLng, json1.stationBeanList, 'mi'); // 输出最近的站点 console.log(nearestStations); // 在地图上标记站点 nearestStations.forEach(station => { const marker = L.marker([station.sLat, station.sLng]); marker.addTo(map_var).bindPopup(`<b>${station.name}</b><br>Distance: ${station.distance} ${station.unit}<br>Available Docks: ${station.availableDocks}`); }); });
这段代码首先定义了起始坐标。 然后,它调用 getStationDistances 函数,并将结果存储在 nearestStations 变量中。 最后,它遍历 nearestStations 数组,并在地图上标记每个站点,并显示一个包含站点名称、距离和可用停靠点的弹出窗口。
5. 完整示例代码
<!DOCTYPE html> <html> <head> <title>Leaflet Nearest Station</title> <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" /> <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <style> #map_id { height: 500px; } </style> </head> <body> <div id="map_id"></div> <script> var map_var = L.map('map_id').setView([40.72730240765651, -73.9939667324035], 16); L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors' }).addTo(map_var); function getDistance(lat1, lon1, lat2, lon2, unit = 'M') { const R = 6371e3; // 地球半径(米) const φ1 = lat1 * Math.PI/180; const φ2 = lat2 * Math.PI/180; const Δφ = (lat2-lat1) * Math.PI/180; const Δλ = (lon2-lon1) * Math.PI/180; const a = Math.sin(Δφ/2) * Math.sin(Δφ/2) + Math.cos(φ1) * Math.cos(φ2) * Math.sin(Δλ/2) * Math.sin(Δλ/2); const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); const d = R * c; // 距离(米) if (unit === 'km') return d * 0.001; if (unit === 'mi') return d * 0.0006213712; return d; } function getStationDistances(locLat, locLng, stationsList, unit = 'mi') { return stationsList.map(station => { const { id, stationName: name, latitude: sLat, longitude: sLng, availableDocks } = station; const distance = Number.parseFloat((Math.round(getDistance( locLat, locLng, sLat, sLng, unit) * 100) / 100).toFixed(2)); return { id, name, distance, unit, sLat, sLng, availableDocks }; }).sort((a, b) => a.distance > b.distance); } $.getJSON("citybike.json", function (json1) { const locationLat = 40.72730240765651; // 起始纬度 const locationLng = -73.9939667324035; // 起始经度 const nearestStations = getStationDistances(locationLat, locationLng, json1.stationBeanList, 'mi'); // 输出最近的站点 console.log(nearestStations); // 在地图上标记站点 nearestStations.forEach(station => { const marker = L.marker([station.sLat, station.sLng]); marker.addTo(map_var).bindPopup(`<b>${station.name}</b><br>Distance: ${station.distance} ${station.unit}<br>Available Docks: ${station.availableDocks}`); }); }); </script> </body> </html>
注意事项:
- 确保 citybike.json 文件与HTML文件位于同一目录下,或者提供正确的路径。
- 根据你的需求调整起始坐标和单位。
- 可以自定义弹出窗口的内容,以显示更多站点信息。
6. 总结
通过本教程,你学习了如何使用Leaflet地图库和JavaScript来计算给定坐标与JSON数据集中自行车站点之间的距离,并找到最近的站点。 你可以将这些技术应用到各种基于位置的服务中,例如查找最近的餐馆、商店或公共交通站点。
大家都在看:
如何构建一个支持多主题切换的CSS架构?
怎样利用CSS Houdini实现浏览器原生级别的动画效果?
CSS 选择器误用导致 animationend 事件失效的排查与解决
JavaScript中的CSS自定义属性(变量)如何动态管理?
原文来自:www.php.cn
暂无评论内容