You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Leaflet.js中用Mapbox路由替换OSM路由

Mapbox替代方案解决OSM路由错误

Got it, let's fix those frustrating 429 (rate limit exceeded) and 400 (bad request) errors you're hitting with OSM routing. The free OSM routing endpoints have strict rate caps that get triggered easily with frequent requests—Mapbox's service is way more reliable for this use case. Here's a drop-in replacement for your Leaflet code:

1. First, add required dependencies

Update your HTML to include Mapbox's Leaflet plugin alongside the core Leaflet files:

<!-- Leaflet base styles -->
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
<!-- Leaflet core library -->
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<!-- Mapbox Leaflet routing plugin -->
<script src="https://unpkg.com/@mapbox/mapbox-leaflet-plugin@latest/dist/mapbox-leaflet-plugin.min.js"></script>

2. Replace your core code

Swap out your original script with this version—make sure to replace YOUR_MAPBOX_ACCESS_TOKEN_HERE with your own token (you can get a free one from the Mapbox website):

// Initialize map with a centered view between your waypoints
var map = L.map('map').setView([34.5997, 98.9834], 4);

// Add Mapbox tile layer (customize style via the `id` parameter)
L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}', {
    attribution: '© Mapbox © OpenStreetMap contributors',
    tileSize: 512,
    maxZoom: 18,
    zoomOffset: -1,
    id: 'mapbox/streets-v12', // Try mapbox/outdoors-v12 for a different look
    accessToken: 'YOUR_MAPBOX_ACCESS_TOKEN_HERE'
}).addTo(map);

// Add Mapbox routing control
L.Routing.control({
    waypoints: [
        L.latLng(15.0991865, 98.9801498),
        L.latLng(54.0810359, 98.9867198)
    ],
    routeWhileDragging: true,
    router: L.Routing.mapbox('YOUR_MAPBOX_ACCESS_TOKEN_HERE')
}).addTo(map);

Quick notes to keep in mind

  • Rate limits are way more forgiving: Mapbox's free tier gives you enough requests for most non-commercial use cases, so 429 errors will be a thing of the past.
  • Stable routing engine: Mapbox's routing service is optimized for reliability, so you'll rarely see 400 errors.
  • Style flexibility: Swap out the id value in the tile layer to use different map styles (like satellite or terrain).
  • Token security: In production, avoid exposing your access token directly in frontend code—use a backend proxy to route requests instead.

内容的提问来源于stack exchange,提问作者Sudharshana

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 06:55:48