Mapbox with custom html element

by amay077

HTML

<script src="https://api.mapbox.com/mapbox-gl-js/v1.6.1/mapbox-gl.js"></script>
<link rel="stylesheet" href="https://api.mapbox.com/mapbox-gl-js/v1.6.1/mapbox-gl.css">
<div id="map" style="position: absolute; top: 0; bottom: 0; width: 100%;"></div>

<template id="marker">
  <table border="1" style="border-collapse: collapse; background-color: #FF00FF40">
    <tr>
      <th>Name</th>
      <th>Age</th>
    </tr>
    <tr>
      <td id="name">name</td>
      <td id="age">age</td>
    </tr>
  </table>
  <div class="marker-container">
    <span id="title" class="marker-title"></span>
    <img id="marker-icon" src="https://img.icons8.com/ios-filled/40/0000FF/marker.png">
  </div>>
</template>

CSS

body { margin: 0; padding: 0; }

JavaScript

const map = new mapboxgl.Map({
  container: 'map',
  center: [134, 35],
  zoom: 10,
  style: {
    version: 8,
    sources: {
      OSM: {
        type: "raster",
        tiles: [
          "https://a.tile.openstreetmap.org/{z}/{x}/{y}.png",
        ],
        tileSize: 256,
        attribution:
        "OpenStreetMap",
      },
    },
    layers: [{
      id: "BASEMAP",
      type: "raster",
      source: "OSM",
      minzoom: 0,
      maxzoom: 18,
    }],
  },      
});


const geojson = {
  'type': 'FeatureCollection',
  'features': [{
      'type': 'Feature',
      'properties': {
        'name': 'Mike',
        'age': 11
      },
      'geometry': {
        'type': 'Point',
        'coordinates': [134.1, 35.05]
      }
    },
    {
      'type': 'Feature',
      'properties': {
        'name': 'Thunder',
        'age': 14
      },
      'geometry': {
        'type': 'Point',
        'coordinates': [133.9, 35]
      }
    },
  ]
};

// add markers to map
geojson.features.forEach(function(marker) {
  // Create element for marker from template
  const template = document.getElementById('marker');
  const clone = document.importNode(template.content, true);
  const el = clone.firstElementChild;
  
  clone.getElementById('name').innerHTML = marker.properties.name;
  clone.getElementById('age').innerHTML = marker.properties.age;

  // add marker to map
  new mapboxgl.Marker(el)
    .setLngLat(marker.geometry.coordinates)
    .addTo(map);
});