Skip to content

Adding Markers to Your Map

The red marker is dragable

This guide demonstrates how to add markers to your MapMetrics map. Follow these steps to get started.

Prerequisites

Before you begin, ensure you have:

Adding a Marker

To add a marker to your map, you can use the Marker class provided by MapMetrics-gl. Here's how to do it:

Example: Adding a Marker

javascript
const marker = new mapmetricsgl.Marker()
  .setLngLat([2.349902, 48.852966]) // Set the marker's position
  .addTo(map); // Add the marker to the map

Customizing Markers

You can customize the appearance of markers by setting properties such as color, size, and icon. For example:

javascript
const marker = new mapmetricsgl.Marker({
  color: "#FF0000", // Red color
  scale: 1.5, // Increase the size
})
  .setLngLat([2.349902, 48.852966])
  .addTo(map);

Creating a Draggable Marker with Custom Color

You can create a marker with a custom color and make it draggable by specifying the color and draggable options in the marker constructor:

javascript
const marker = new mapmetricsgl.Marker({
  color: "#FFFFFF",    // White marker
  draggable: true      // Make the marker draggable
})
  .setLngLat([30.5, 50.5])
  .addTo(map);

You can also listen for drag events to get the marker's new position:

javascript
marker.on('dragend', function() {
  const lngLat = marker.getLngLat();
  console.log('Marker dropped at', lngLat);
});

Complete Example

Here's a complete example of how to add a marker to your map:

html
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link
      href="https://cdn.mapmetrics-atlas.net/versions/latest/mapmetrics-gl.css"
      rel="stylesheet"
    />
    <script src="https://cdn.mapmetrics-atlas.net/versions/latest/mapmetrics-gl.js"></script>
    <style>
      html,
      body {
        margin: 0;
        padding: 0;
        height: 100%;
      }
      #map {
        min-height: 500px;
        height: 100%;
        width: 100%;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>
    <script>
      // Don't forget to replace <YOUR_ACCESS_TOKEN> with your own access style/accesstoken
      const accessToken = "<YOUR_ACCESS_TOKEN>";
      const map = new mapmetricsgl.Map({
        container: "map",
        style: `${accessToken}`,
        zoom: 11,
        center: [2.349902, 48.852966],
      }).addControl(new mapmetricsgl.NavigationControl(), "top-right");

      // Add a marker with the default icon
      new mapmetricsgl.Marker().setLngLat([2.349902, 48.852966]).addTo(map);
    </script>
  </body>
</html>

For more information, visit the MapMetrics GitHub repository.