在Mapbox地图上添加自定义标记

4

我在我的项目中使用了Mapbox。

我之前使用了Mapbox.js,并且创建了带有自定义标记的地图,代码如下:

 $(function() { 
  const token = '*********';
  let myLatlng = L.latLng(<%= @hotel.lat %>,<%= @hotel.lng %>);
  L.mapbox.accessToken = token;
  let map = L.mapbox.map('map-canvas', 'mapbox.streets')
  .setView(myLatlng, 14);

  let marker = new L.marker(myLatlng,{
    icon: L.icon({
        iconUrl: '//chart.googleapis.com/chart?chst=d_map_pin_icon&chld=home|EBCB2D'
      })
  }).addTo(map);
  });

我正在更改标记的图标,像这样:

  icon: L.icon({
        iconUrl: '//chart.googleapis.com/chart?chst=d_map_pin_icon&chld=home|EBCB2D'
      })

我想知道MapBox GL JS是否有类似于这样的简写方法来更改它?

您可以使用addImage: https://www.mapbox.com/mapbox-gl-js/example/add-image/ - stdob--
或者您可以通过创建一个img元素来使用GL JS标记。 - AndrewHarvey
3个回答

7
为了解释这两个评论,有两种不同的方法可以将自定义图像添加到地图中:

使用符号层

符号层存在于地图中,可用于可视化数据源。

首先,使用loadImage()获取图像URL:

map.loadImage('https://example.com/image.png', function(error, image) {
    if (error) throw error;

接下来,使用addImage()将获取的图片转换为地图中的图标:

   map.addImage('pin', image);

最后,将该图标用在一个图层上:
   map.addLayer({ id: 'mypin', type: 'symbol', paint: { 'icon-image': 'pin' });

完整示例:https://www.mapbox.com/mapbox-gl-js/example/add-image/

使用标记

或者,您可以使用标记。这个标记存在于地图上方,不与其中的数据交互。

首先,创建用于图像的 DOM 元素:

var el = document.createElement('div');
el.className = 'marker';
el.style.backgroundImage = 'url(https://example.com/icon.png)';
el.style.width = '20px';
el.style.height = '20px';

接下来,根据此元素创建一个标记对象,并将其添加到地图中:
new mapboxgl.Marker(el)
    .setLngLat(mylatlng)
    .addTo(map);

完整示例:https://www.mapbox.com/mapbox-gl-js/example/custom-marker-icons/

在性能方面,哪一个更好? - Eusthace

0

我强烈建议用以下方式解决这个问题:

首先创建要替换旧标记的元素:

const customMarker = document.createElement('div');
customMarker.style.backgroundImage = 'url(../../../assets/images/pin.svg)';
customMarker.style.backgroundSize = 'cover';
customMarker.style.backgroundPosition = 'center';
customMarker.style.width = '27px';
customMarker.style.height = '41px';

然后使用选项对象作为参数创建标记对象,并设置以下属性:

 const marker = new mapboxgl.Marker({
    anchor: 'bottom',
    element: customMarker,
  })
   .setLngLat([this.lng, this.lat])
   .addTo(map);

因为,如果你用其他方法解决这个问题,标记将会在地图上几乎随机放置,这会使用户体验看起来很糟糕。

使用我的解决方案的示例:

example

其他解决方案示例:

example2

更多细节请查看文档的这一部分: 文档


0
你可以轻松地像这样使用。这段代码是从Mapbox网站找到的。
var marker = new mapboxgl.Marker({
  element: createCustomMarkerElement('./assets/images/heart.png'),
})
.setLngLat([location.lng, location.lat])
.addTo(map);

customMarker函数是什么?
function createCustomMarkerElement(imagePath) {
    const el = document.createElement('div');
    const width = 50;
    const height = 55;
    el.className = 'marker';
    el.style.backgroundImage = 'url(' + imagePath + ')';
    el.style.width = `${width}px`;
    el.style.height = `${height}px`;
    el.style.backgroundSize = '100%';
    return el;
 }

最后,您可以像这样使用一些样式。
<style>
.marker {
  display: block;
  border: none;
  border-radius: 50%;
  cursor: pointer;
  padding: 0;
}
</style>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接