Mapbox 自定义标记旋转

Mat*_*ure 3 html angle rotation marker mapbox

在遵循 mapbox 教程之后,我设法在地图上显示了一架无人机。我唯一的问题是:如何在我的代码中添加旋转参数(以不同角度显示无人机标记)?我花了几个小时寻找例子,但没有一个与我已经写的相对应......

谢谢 !

这是脚本:

<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8' />
    <title></title>
    <meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
    <link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
    <script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.43.0/mapbox-gl.js'></script>
    <link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.43.0/mapbox-gl.css' rel='stylesheet' />
    <style>
      body {
        margin: 0;
        padding: 0;
      }

      #map {
        position: absolute;
        top: 0;
        bottom: 0;
        width: 100%;
    
      }
      
      .marker {
          background-image: url('MQ-1_Predator_silhouette.svg.png');
          background-size: cover;
          width: 61px;
          height: 35px;
          border-radius: 50%;
          cursor: pointer;
        
        }
        
    </style>
</head>
<body>

<div id='map'></div>

<script>

mapboxgl.accessToken = 'pk.eyJ1IjoibWF0dGhpZXU2MyIsImEiOiJjamNob3I3cmgxam1kMzFzNzdja2ZvNmhuIn0.AyFos9o0afaaBU21CgrxXg';

var map = new mapboxgl.Map({
  container: 'map',
  style: 'mapbox://styles/mapbox/light-v9',
  center: [-96, 37.8],
  zoom: 3
});



// code from the next step will go here!

var geojson = {
  type: 'FeatureCollection',
  features: [{
    type: 'Feature',
    geometry: {
      type: 'Point',
      coordinates: [-90,40]
    },
    properties: {
      title: 'Mapbox'
    }
  }]
};

// add markers to map
geojson.features.forEach(function(marker) {

  // create a HTML element for each feature
  var el = document.createElement('div');
  el.className = 'marker';

  // make a marker for each feature and add to the map
  new mapboxgl.Marker(el)
  .setLngLat(marker.geometry.coordinates)
  .addTo(map);
});

</script>

</body>
</html>
Run Code Online (Sandbox Code Playgroud)

小智 5

Mapbox 在获取方位的标题下提供内置的图标旋转功能,一旦您发现两对 LatLng 之间的地理方位并提供该值以获取方位,就会在内部处理图标旋转。

如果您正在使用 mapbox 标记并热衷于旋转它,您可以使用 css 变换属性 (rotate()) 并动态计算两对 latLng 之间的角度并在旋转属性中使用该值。

        var dLon = destination[0]-origin[0];
        var dLat = destination[1]-origin[1];
        var angle = 180+(Math.atan2(dLon, dLat) * 180 / Math.PI);
        var rotateString = "rotate(" + angle + "deg)";

        var el = document.createElement('div');
        el.className = 'marker';
        var truckMarker = new mapboxgl.Marker(el)
        el.style.transform = el.style.transform + rotateString;
Run Code Online (Sandbox Code Playgroud)

在最后一行中,附加rotate 属性很重要,因为transform 属性已经在因为动画而被调用translate 时被更新。对我来说效果很好!!