首页 > 解决方案 > 使用 Mapbox 指定营业地点的坐标

问题描述

我确定这是一件非常简单的事情,但是如何使用 Mapbox 包含地图的坐标?该产品是嵌入在网站上的简单地图,在商店位置有一个标记。该公司位于西非的加纳。坐标为 [5.6513286, -0.1945831]。

<script>
mapboxgl.accessToken = '';
var map = new mapboxgl.Map({
container: 'map',
center: [5.6513286, -0.1945831],
zoom: 5,
style: 'mapbox://styles/kopoku/ck826mkp719ne1iruuq8bpjmk'
});

var marker = new mapboxgl.Marker()
  .setLngLat([5.6513286, -0.1945831])
  .addTo(map);


</script>

标签: mapbox

解决方案


为了实现这一点,您需要向地图添加一个包含作为GeoJSON特征的坐标的GeoJSON 源,以及一个其属性设置为包含要使用表达式显示的坐标的字符串的图层symboltext-fieldget

map.on('load', function() {

  map.addSource('point', {
    'type': 'geojson',
    'data': {    
      // feature for the coordinate to display
      'type': 'Feature',
      'geometry': {
        'type': 'Point',
        'coordinates': [-0.1945831, 5.6513286]
      },
      'properties': {
        'coordinates': '[-0.1945831, 5.6513286]',
      }
    }
  });

  map.addLayer({
    'id': 'point',
    'type': 'symbol',
    'source': 'point',
    'layout': {
      // get the coordinates from the source's "coordinates" property
      'text-field': ['get', 'coordinates'],
      'text-font': ['Open Sans Semibold', 'Arial Unicode MS Bold'],
    }
  });

});

另外,请注意,我将中心坐标的顺序切换为[5.6513286, -0.1945831][-0.1945831, 5.6513286]因为原点位于海洋而不是加纳。这表示原始纬度和经度值被翻转。

这是一个包含所有代码的 JSFiddle:https ://jsfiddle.net/yLz29m1g/ 。请注意,您需要在指示的位置添加自己的 Mapbox 访问令牌才能查看结果。这是一个截图作为预览:

在此处输入图像描述


推荐阅读