将自定义标记添加到 Mapbox 地图

问题描述 投票:0回答:3

我在我的项目中使用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是否有像rhis这样的简写方法来改变它?

javascript jquery mapbox mapbox-gl-js
3个回答
6
投票

为了阐明给出的两条注释,有两种不同的方法可以将自定义图像添加到地图:

使用符号图层

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

首先,使用

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';

接下来,根据该元素创建一个Marker对象,并将其添加到地图中:

new mapboxgl.Marker(el)
    .setLngLat(mylatlng)
    .addTo(map);

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


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

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

我的解决方案示例:

其他解决方案的示例:

有关更多详细信息,请查看文档的这一部分: 文档


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>

我希望这段代码能对您有所帮助。快乐编码

© www.soinside.com 2019 - 2024. All rights reserved.