// 初始化地图 const map = L.map('map').setView([31.2304, 121.4737], 13); // 上海坐标 L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 19, attribution: '© OpenStreetMap' }).addTo(map); let markers = []; let routeLine = null; // 点击地图添加起点/终点 map.on('click', async (e) => { const { lat, lng } = e.latlng; if (markers.length >= 1) { // 重置 markers.forEach(m => map.removeLayer(m)); markers = []; if (routeLine) { map.removeLayer(routeLine); routeLine = null; } } const marker = L.marker([lat, lng]).addTo(map); markers.push(marker); const url = `https://nominatim.openstreetmap.org/reverse?format=jsonv2&lat=${lat}&lon=${lng}`; const res = await fetch(url); const data = await res.json(); console.log(data); marker.bindPopup(`📍 当前位置:
纬度:${lat}
经度:${lng}
${data.display_name}`).openPopup(); console.log("选择的坐标:", lat, lng); if (markers.length === 2) { const start = markers[0].getLatLng(); const end = markers[1].getLatLng(); // 请求 OSRM 路线 API const url = `https://router.project-osrm.org/route/v1/driving/${start.lng},${start.lat};${end.lng},${end.lat}?overview=full&geometries=geojson`; const response = await fetch(url); const json = await response.json(); if (json.code === 'Ok') { const coords = json.routes[0].geometry.coordinates.map(c => [c[1], c[0]]); routeLine = L.polyline(coords, { color: 'blue', weight: 5 }).addTo(map); map.fitBounds(routeLine.getBounds()); const distance = (json.routes[0].distance / 1000).toFixed(2); const duration = (json.routes[0].duration / 60).toFixed(1); alert(`路线规划完成:\n距离:${distance} 公里\n预计时间:${duration} 分钟`); } else { alert('路线规划失败'); } } }); document.addEventListener('UniAppJSBridgeReady', function() { function initMap() { uni.postMessage({ data: { mark:"initMap" } }); } window.initMap = initMap; });