Add a marker

Estimated reading time: 1 minute

Check out this code sample that uses the MapLibre GL JS library to add a marker from GeoJSON onto your map.

View on GitHub

<!doctype html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link href="https://unpkg.com/[email protected]/dist/maplibre-gl.css" rel="stylesheet" />
    <script src="https://unpkg.com/[email protected]/dist/maplibre-gl.js"></script>
    <style>
      html,
      body {
        margin: 0;
        padding: 0;
        height: 100%;
      }
      #map {
        min-height: 500px;
        height: 100%;
        width: 100%;
      }
      .marker {
        background-image: url("https://www.jawg.io/docs/images/icons/[email protected]");
        background-size: cover;
        width: 50px;
        height: 50px;
        cursor: pointer;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>
    <script>
      // Don't forget to replace <YOUR_ACCESS_TOKEN> by your own access token
      const accessToken = "<YOUR_ACCESS_TOKEN>";
      const map = new maplibregl.Map({
        container: "map",
        style: `https://api.jawg.io/styles/jawg-streets.json?access-token=${accessToken}`,
        zoom: 11,
        center: [2.349902, 48.852966],
      }).addControl(new maplibregl.NavigationControl(), "top-right");
      // This plugin is used for right to left languages
      maplibregl.setRTLTextPlugin("https://unpkg.com/@mapbox/[email protected]/mapbox-gl-rtl-text.min.js");

      // Add a marker with the default icon
      new maplibregl.Marker().setLngLat([2.349902, 48.852966]).addTo(map);

      // Add a Marker with a custom icon.
      // Check all the marker options here: https://maplibre.org/maplibre-gl-js/docs/API/type-aliases/MarkerOptions/
      const el = document.createElement("div");
      el.addEventListener("click", () => {
        window.alert("Eiffel Tower");
      });

      // add marker to map
      new maplibregl.Marker({
        className: "marker",
        element: el,
      })
        .setLngLat([2.294694, 48.858093])
        .addTo(map);
    </script>
  </body>
</html>