Skip to content

Locate the User

Show the user's current GPS location on the map using the built-in GeolocateControl or the browser's Geolocation API.

Click the 🎯 button (top-right of map) or the button above to locate yourself.

Two Ways to Locate the User

The easiest approach — adds a 🎯 button to the map that handles everything automatically.

javascript
const geolocate = new mapmetricsgl.GeolocateControl({
  positionOptions: { enableHighAccuracy: true },
  trackUserLocation: true,   // Continuously tracks user movement
  showUserHeading: true      // Shows direction user is facing
});

map.addControl(geolocate, 'top-right');

// Listen for location events
geolocate.on('geolocate', (e) => {
  const { longitude, latitude } = e.coords;
  console.log(`User at: ${longitude}, ${latitude}`);
});

geolocate.on('error', (e) => {
  console.error('Geolocation error:', e);
});

Option 2: Browser Geolocation API (Manual)

Use the browser's navigator.geolocation API directly for more control.

javascript
navigator.geolocation.getCurrentPosition(
  (position) => {
    const { longitude, latitude } = position.coords;

    // Fly to user location
    map.flyTo({ center: [longitude, latitude], zoom: 14 });

    // Add marker at user location
    new mapmetricsgl.Marker({ color: '#22c55e' })
      .setLngLat([longitude, latitude])
      .setPopup(
        new mapmetricsgl.Popup({ offset: 25 })
          .setHTML('<strong>You are here!</strong>')
      )
      .addTo(map);
  },
  (error) => {
    console.error('Error getting location:', error.message);
  },
  { enableHighAccuracy: true }
);

GeolocateControl Options

OptionTypeDescription
positionOptions.enableHighAccuracybooleanUse GPS for better accuracy
trackUserLocationbooleanContinuously update position as user moves
showUserHeadingbooleanShow compass direction arrow
showAccuracyCirclebooleanShow accuracy radius circle (default: true)

Complete Example

html
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <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 { height: 500px; width: 100%; }
      button { margin-top: 10px; padding: 8px 16px; background: #3b82f6; color: white; border: none; border-radius: 6px; cursor: pointer; }
    </style>
  </head>
  <body>
    <div id="map"></div>
    <button onclick="locateMe()">📍 Locate Me</button>
    <script>
      const map = new mapmetricsgl.Map({
        container: 'map',
        style: '<StyleFile_URL_with_Token>',
        center: [0, 20],
        zoom: 2
      });

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

      // Option 1: Built-in GeolocateControl (adds a 🎯 button)
      const geolocate = new mapmetricsgl.GeolocateControl({
        positionOptions: { enableHighAccuracy: true },
        trackUserLocation: true,
        showUserHeading: true
      });
      map.addControl(geolocate, 'top-right');

      // Option 2: Manual button using browser API
      function locateMe() {
        if (!navigator.geolocation) {
          alert('Geolocation is not supported by your browser.');
          return;
        }

        navigator.geolocation.getCurrentPosition(
          (position) => {
            const { longitude, latitude } = position.coords;

            map.flyTo({ center: [longitude, latitude], zoom: 14, speed: 1.5 });

            new mapmetricsgl.Marker({ color: '#22c55e' })
              .setLngLat([longitude, latitude])
              .setPopup(new mapmetricsgl.Popup({ offset: 25 }).setHTML('<strong>You are here!</strong>'))
              .addTo(map);
          },
          (error) => {
            alert('Could not get your location: ' + error.message);
          },
          { enableHighAccuracy: true }
        );
      }
    </script>
  </body>
</html>
jsx
import React, { useEffect, useRef, useState } from 'react';
import mapmetricsgl from '@mapmetrics/mapmetrics-gl';
import '@mapmetrics/mapmetrics-gl/dist/mapmetrics-gl.css';

const LocateUser = () => {
  const mapContainer = useRef(null);
  const map = useRef(null);
  const [status, setStatus] = useState('');

  useEffect(() => {
    if (map.current) return;

    map.current = new mapmetricsgl.Map({
      container: mapContainer.current,
      style: '<StyleFile_URL_with_Token>',
      center: [0, 20],
      zoom: 2
    });

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

    // Built-in GeolocateControl
    const geolocate = new mapmetricsgl.GeolocateControl({
      positionOptions: { enableHighAccuracy: true },
      trackUserLocation: true,
      showUserHeading: true
    });

    map.current.addControl(geolocate, 'top-right');

    geolocate.on('geolocate', (e) => {
      const { longitude, latitude } = e.coords;
      setStatus(`📍 Your location: Lng: ${longitude.toFixed(5)} | Lat: ${latitude.toFixed(5)}`);
    });

    geolocate.on('error', () => {
      setStatus('❌ Could not get your location. Please allow location access.');
    });

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

  const locateManually = () => {
    setStatus('⏳ Getting your location...');

    if (!navigator.geolocation) {
      setStatus('❌ Geolocation not supported by your browser.');
      return;
    }

    navigator.geolocation.getCurrentPosition(
      (pos) => {
        const { longitude, latitude } = pos.coords;
        setStatus(`📍 Your location: Lng: ${longitude.toFixed(5)} | Lat: ${latitude.toFixed(5)}`);

        map.current?.flyTo({ center: [longitude, latitude], zoom: 14, speed: 1.5 });

        new mapmetricsgl.Marker({ color: '#22c55e' })
          .setLngLat([longitude, latitude])
          .setPopup(new mapmetricsgl.Popup({ offset: 25 }).setHTML('<strong>You are here!</strong>'))
          .addTo(map.current);
      },
      (error) => {
        setStatus(`❌ Error: ${error.message}`);
      },
      { enableHighAccuracy: true }
    );
  };

  return (
    <div>
      <div ref={mapContainer} style={{ height: '500px', width: '100%' }} />
      <div style={{ marginTop: '10px', display: 'flex', gap: '8px', alignItems: 'center', flexWrap: 'wrap' }}>
        <button
          onClick={locateManually}
          style={{ padding: '8px 16px', background: '#3b82f6', color: 'white', border: 'none', borderRadius: '6px', cursor: 'pointer' }}
        >
          📍 Locate Me
        </button>
        {status && (
          <div style={{ padding: '8px 12px', background: '#1e293b', color: '#e2e8f0', borderRadius: '6px', fontFamily: 'monospace', fontSize: '14px' }}>
            {status}
          </div>
        )}
      </div>
    </div>
  );
};

export default LocateUser;

⚠️ Note: Geolocation requires the user to grant browser permission and only works over HTTPS in production.


For more information, visit the MapMetrics GitHub repository.