Skip to content

JavaScript Quickstart

Vanilla JS / browser, no framework. For React/Vue/Svelte/Angular see docs/frameworks/.

Install

CDN:

html
<link href="https://unpkg.com/maplibre-gl@4/dist/maplibre-gl.css" rel="stylesheet">
<script src="https://unpkg.com/maplibre-gl@4/dist/maplibre-gl.js"></script>

npm:

bash
npm install maplibre-gl

Render a map

html
<div id="map" style="width:100%;height:100vh"></div>
<script>
  const PUB_KEY = 'mfd_pub_xxxxxxxx';
  const map = new maplibregl.Map({
    container: 'map',
    style: `https://api.mapsfordevs.com/styles/standard.json?key=${PUB_KEY}`,
    center: [28.04, -26.20],
    zoom: 11
  });
</script>

Add a marker

js
new maplibregl.Marker()
  .setLngLat([28.04, -26.20])
  .setPopup(new maplibregl.Popup().setText('Office'))
  .addTo(map);

Switch language at runtime

js
function setLang(map, lang) {
  ['place_label', 'transportation_name', 'poi_label'].forEach(layer => {
    map.setLayoutProperty(layer, 'text-field', [
      'coalesce',
      ['get', `name:${lang}`],
      ['get', 'name:latin'],
      ['get', 'name']
    ]);
  });
}
map.on('load', () => setLang(map, 'de'));

Geocode (phase 3)

js
async function geocode(query) {
  const r = await fetch(
    `https://api.mapsfordevs.com/geocode/forward?q=${encodeURIComponent(query)}&limit=5`,
    { headers: { Authorization: `Bearer ${PUB_KEY}` } }
  );
  return r.json();
}

Cleanup

js
window.addEventListener('beforeunload', () => map.remove());

Errors

js
map.on('error', e => console.error('map error', e.error?.status, e.error?.message));
StatusCauseFix
401Bad/missing keyCheck key prefix mfd_pub_
403Domain not in allow-listAdd domain in dashboard
429Burst rate limitHonour Retry-After
402Free quota goneUpgrade plan