Skip to content

Simple Map with CDN Installation

This guide demonstrates how to quickly set up a MapMetrics map using our CDN. Follow these steps to get started.

Prerequisites

Before you begin, ensure you have:

Installation with CDN

Add the following lines to the <head> of your HTML file:

html
<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>

Tip: Using the CDN is ideal for quick prototypes and demos. For production, consider using a package manager for better version control.

2. Create the Map Container

Add a <div> element to your HTML where the map will be rendered:

html
<div id="map"></div>

3. Style the Map Container

Add the following CSS to ensure the map displays correctly:

html
<style scoped>
  #map {
    min-height: 500px;
    height: 500px;
    width: 100%;
  }
</style>

⚠️ Important

Don’t forget to add <StyleFile_URL_with_Token> during intialization of map.
You can get them from: http://portal.mapmetrics.org/

4. Initialize the Map

Use the following JavaScript to initialize the map. Replace <StyleFile_URL_with_Token> with style URL and Connect API Key that you get from https://portal.mapmetrics.org/:

html
<script>
     const styleFileWithToken = "<StyleFile_URL_with_Token>";

  const cssLink = document.createElement("link");
  cssLink.rel = "stylesheet";
  cssLink.href =
    "https://cdn.mapmetrics-atlas.net/versions/latest/mapmetrics-gl.css";
  document.head.appendChild(cssLink);

  const script = document.createElement("script");
  script.src =
    "https://cdn.mapmetrics-atlas.net/versions/latest/mapmetrics-gl.js";
  document.body.appendChild(script);

  script.onload = () => {
    const map = new mapmetricsgl.Map({
      container: "map",
      style: `${styleFileWithToken}`,
      zoom: 11,
      center: [2.349902, 48.852966],
      attributionControl: {
        compact: false,
        position: "bottom-right",
      },
    }).addControl(new mapmetricsgl.NavigationControl(), "top-right");
  };
</script>

For better user experience, add error handling to detect missing or invalid tokens:

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>
      #map {
        min-height: 500px;
        height: 500px;
        width: 100%;
      }
      .error-box {
        height: 500px;
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: #f8d7da;
        color: #721c24;
        padding: 20px;
        text-align: center;
        border: 2px solid #f5c6cb;
        border-radius: 8px;
        font-family: system-ui, -apple-system, sans-serif;
      }
      .loading-box {
        height: 500px;
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: #f0f0f0;
        color: #666;
        font-size: 16px;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>

    <script>
      const styleFileWithToken = "<StyleFile_URL_with_Token>";
      const mapContainer = document.getElementById('map');

      // Check if user forgot to replace the placeholder
      if (styleFileWithToken === '<StyleFile_URL_with_Token>' || styleFileWithToken.includes('<') || styleFileWithToken.includes('YOUR_')) {
        mapContainer.innerHTML = `
          <div class="error-box">
            <div>
              <strong>⚠️ Please replace &lt;StyleFile_URL_with_Token&gt; with your actual style URL from https://portal.mapmetrics.org/</strong>
              <div style="margin-top: 10px; font-size: 14px;">
                Need help? Check the <a href="https://discord.com/invite/uRXQRfbb7d" style="color: #721c24; text-decoration: underline;">Discord community</a>
              </div>
            </div>
          </div>
        `;
      } else {
        // Show loading state
        mapContainer.innerHTML = '<div class="loading-box">Loading map...</div>';

        try {
          const map = new mapmetricsgl.Map({
            container: 'map',
            style: styleFileWithToken,
            zoom: 11,
            center: [2.349902, 48.852966],
            attributionControl: {
              compact: false,
              position: 'bottom-right'
            }
          });

          // Handle successful load
          map.on('load', () => {
            console.log('Map loaded successfully');
          });

          // Handle critical errors (401, style loading failures)
          map.on('error', (e) => {
            console.error('Map error:', e);

            // Only show error UI for critical failures
            const isCriticalError =
              e.error?.status === 401 ||
              e.error?.message?.includes('401') ||
              e.error?.message?.includes('Failed to fetch') ||
              (e.sourceId === undefined && e.error);

            if (isCriticalError) {
              let errorMessage = '❌ Map failed to load. Check your style URL and token at https://portal.mapmetrics.org/';

              if (e.error?.status === 401 || e.error?.message?.includes('401')) {
                errorMessage = '❌ Invalid API token. Get a valid token from https://portal.mapmetrics.org/';
              } else if (e.error?.message?.includes('Failed to fetch')) {
                errorMessage = '❌ Cannot load map style. Check your style URL from https://portal.mapmetrics.org/';
              }

              mapContainer.innerHTML = `
                <div class="error-box">
                  <div>
                    <strong>${errorMessage}</strong>
                    <div style="margin-top: 10px; font-size: 14px;">
                      Need help? Check the <a href="https://discord.com/invite/uRXQRfbb7d" style="color: #721c24; text-decoration: underline;">Discord community</a>
                    </div>
                  </div>
                </div>
              `;
            } else {
              // Non-critical error, just log it
              console.warn('Non-critical map error:', e);
            }
          });

          // Add navigation controls
          map.addControl(new mapmetricsgl.NavigationControl(), 'top-right');

        } catch (err) {
          console.error('Map initialization error:', err);
          mapContainer.innerHTML = `
            <div class="error-box">
              <div>
                <strong>❌ Failed to initialize map. Check your style URL from https://portal.mapmetrics.org/</strong>
                <div style="margin-top: 10px; font-size: 14px;">
                  Need help? Check the <a href="https://discord.com/invite/uRXQRfbb7d" style="color: #721c24; text-decoration: underline;">Discord community</a>
                </div>
              </div>
            </div>
          `;
        }
      }
    </script>
  </body>
</html>

Complete Example (Basic - Without Error Handling)

Here's a basic HTML example for reference (without error handling):

html
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <style>
      #map {
        min-height: 500px;
        height: 500px;
        width: 100%;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>

    <script>
    const styleFileWithToken = "<StyleFile_URL_with_Token>";

      const cssLink = document.createElement("link");
      cssLink.rel = "stylesheet";
      cssLink.href =
        "https://cdn.mapmetrics-atlas.net/versions/latest/mapmetrics-gl.css";
      document.head.appendChild(cssLink);

      const script = document.createElement("script");
      script.src =
        "https://cdn.mapmetrics-atlas.net/versions/latest/mapmetrics-gl.js";
      document.body.appendChild(script);

      script.onload = () => {
        const map = new mapmetricsgl.Map({
          container: "map",
          style: `${styleFileWithToken}`,
          zoom: 11,
          center: [2.349902, 48.852966],
          attributionControl: {
            compact: false,
            position: "bottom-right",
          },
        }).addControl(new mapmetricsgl.NavigationControl(), "top-right");
      };
    </script>
  </body>
</html>

⚠️ Important
NPM Package available here: https://www.npmjs.com/package/@mapmetrics/mapmetrics-gl

jsx
import React, { useEffect, useRef } from "react";
import mapmetricsgl from "@mapmetrics/mapmetrics-gl";
import "@mapmetrics/mapmetrics-gl/dist/mapmetrics-gl.css";

const SimpleMap = () => {
  const mapContainerRef = useRef(null);
  const mapRef = useRef(null);

  useEffect(() => {
    if (!mapContainerRef.current || mapRef.current) return;

    const styleFileWithToken = "<StyleFile_URL_with_Token>";

    const map = new mapmetricsgl.Map({
      container: mapContainerRef.current,
      style: `${styleFileWithToken}`,
      zoom: 11,
      center: [2.349902, 48.852966],
    });

    map.addControl(new mapmetricsgl.NavigationControl(), "top-right");

    mapRef.current = map;

    return () => {
      map.remove();
      mapRef.current = null;
    };
  }, []);

  return (
    <div
      ref={mapContainerRef}
      style={{
        minHeight: "500px",
        height: "100%",
        width: "100%",
      }}
    />
  );
};

export default SimpleMap;

Map Container Example

Here's an example of how the map container looks in action:


For more information, visit the MapMetrics GitHub repository.