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

时间:2017-05-26 18:38:35

标签: javascript html mapbox-gl-js

我正在尝试在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>

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

建议/示例?

1 个答案:

答案 0 :(得分:2)

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

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);
});