
同时,确保你有一个包含自行车站点信息的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: '© OpenStreetMap 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(`${station.name}
Distance: ${station.distance} ${station.unit}
Available Docks: ${station.availableDocks}`); });});
这段代码首先定义了起始坐标。 然后,它调用 getStationDistances 函数,并将结果存储在 nearestStations 变量中。 最后,它遍历 nearestStations 数组,并在地图上标记每个站点,并显示一个包含站点名称、距离和可用停靠点的弹出窗口。
5. 完整示例代码
Leaflet Nearest Station #map_id { height: 500px; } 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: '© OpenStreetMap 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(`${station.name}
Distance: ${station.distance} ${station.unit}
Available Docks: ${station.availableDocks}`); }); });
注意事项:
确保 citybike.json 文件与HTML文件位于同一目录下,或者提供正确的路径。根据你的需求调整起始坐标和单位。可以自定义弹出窗口的内容,以显示更多站点信息。
6. 总结
通过本教程,你学习了如何使用Leaflet地图库和JavaScript来计算给定坐标与JSON数据集中自行车站点之间的距离,并找到最近的站点。 你可以将这些技术应用到各种基于位置的服务中,例如查找最近的餐馆、商店或公共交通站点。
以上就是使用Leaflet查找最近的坐标点:计算与JSON数据集中自行车站点距离的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1524238.html
微信扫一扫
支付宝扫一扫