如何向 MapBox GL JS 地图添加标记?

2023-12-03

我正在尝试将标记添加到 HTML / Javascript 地图中的 MapBox-GL-JS 地图。

我尝试构建一个小示例:这是我的代码

<html>
  <head>
    <meta charset="utf-8">
    <title>Test MapBox</title>

    <!-- *** References for MapBox GL JS ... -->
        <script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.37.0/mapbox-gl.js'></script>
    <link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.37.0/mapbox-gl.css' rel='stylesheet' />

    <style>
      html, body {
        min-height: 100%;
        min-width: 100%;
        margin: 0;
        padding: 0;
      }
      table {
        width: 95vw;
        height: 95vh;
      }
      td {
        width: 50%;
        height: 50%;
      }
   </style>
  </head>
  <body>
    <div id="maps-images">
     <center>
      <table border=1>
       <!-- second row -->
       <tr id="row2">
         <td id="osm">
           <div id="osm_map" style="width:100%;height:100%"></div>
         </td>
       </tr>
      </table>
    </center>
    </div>

    <script>
      mapboxgl.accessToken = '<PUT_YOUR_MAPBOX_KEY_HERE';
      // *** Create and configure the map ...
      var osm_map = new mapboxgl.Map({
          container: 'osm_map', // container id
          style: 'mapbox://styles/mapbox/bright-v9', //stylesheet location
          center: [13.291408333333237,42.628386111111126], // starting position
          zoom: 16 // starting zoom
      });
      // *** Add zoom and rotation controls to the map ...
      osm_map.addControl(new mapboxgl.NavigationControl());

      marker = new mapboxgl.Marker()
        .setLngLat([13.291408333333237, 42.628386111111126])
        .addTo(osm_map);

    </script>
  </body>
</html>

该代码工作正常,但我的地图上没有显示标记......

建议/例子?


标记没有任何默认样式。您需要创建一个 HTML 元素并传递它。参见示例here:

var el = document.createElement('div');
    el.className = 'marker';
    el.style.backgroundImage = 'url(https://placekitten.com/g/' + marker.properties.iconSize.join('/') + '/)';
    el.style.width = marker.properties.iconSize[0] + 'px';
    el.style.height = marker.properties.iconSize[1] + 'px';

    el.addEventListener('click', function() {
        window.alert(marker.properties.message);
    });

    // add marker to map
    new mapboxgl.Marker(el, {offset: [-marker.properties.iconSize[0] / 2, -marker.properties.iconSize[1] / 2]})
        .setLngLat(marker.geometry.coordinates)
        .addTo(map);
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何向 MapBox GL JS 地图添加标记? 的相关文章