在MapBox中获取标记功能实例

问题描述 投票:1回答:2

我是mapbox GL JS的新手,我遵循这个例子:在Mapbox GL JS中添加自定义标记https://www.mapbox.com/help/custom-markers-gl-js/

假设我修改上面的示例以包含100种不同的动物标记。将特定标记添加到地图后,如何更改其可拖动属性?

示例:更改狗标记的可拖动属性。

做这样的事情会很好:map.getMarker('dog')。setDraggable(true);

我没有看到一种方法来查询添加到我的地图中的任何标记,或者在添加到地图后修改特定标记的属性,如setLatLng,setDraggable。没有方法可以将标记集合添加到地图中。谢谢你的帮助!

mapbox marker
2个回答
0
投票

对于更改标记属性,如draggable检查其api。 IE https://www.mapbox.com/mapbox-gl-js/api/#marker#setdraggable

Mapbox自定义标记由html元素构建。如果要更改自定义标记元素的可视显示,则应更新其内部html。例如,这里有2个函数,我用它来创建一个带有图像背景的div,然后将其作为图像标记返回

    /**
     *  @function CustomMarkerWithIcon(): constructor for CustomMarker with image icon specify
     *  @param lnglat: (LngLat) position of the marker
     *            map: (Map) map used on
     *           icon: (image) object for custom image
     */
    function CustomMarkerWithIcon(lnglat, map, icon) {
        var el = document.createElement('div');
        el.className = 'marker';
        el.style.backgroundImage = 'url("' + icon.url + '")';
        el.style.backgroundSize = 'cover';
        el.style.width = icon.size.width;
        el.style.height = icon.size.height;
        el.style.zIndex = icon.zIndex;

        return new mapboxgl.Marker(el)
                    .setLngLat(lnglat)
                    .addTo(map);
    }


    /**
     *  @function ChangeMarkerIcon(): change marker icon
     *  @param marker: (marker) marker
     *           icon: (image) object for custom image
     */
    function ChangeMarkerIcon(marker, icon) {
        var el = marker.getElement();
        el.style.backgroundImage = 'url("' + icon.url + '")';
    }

0
投票

你是对的:Mapbox GL JS doesn't store references to markers。但是,您可以在生成数组时将自己的引用存储在数组中。

在下面的示例中,我循环遍历一组GeoJSON点要素并为每个要素创建自定义HTML标记:

let markersArray = [];

geojson.features.forEach(feature => {
  // create a HTML element for each feature
  let el = document.createElement("div");
  el.className = "marker";
  el.innerHTML = `
    <img src="custom-marker.png" height="20px" width="20px" />
    <span class="marker-label">${feature.properties.name}</span>
  `;

  // make a marker for each feature and add to the map
  let marker = new mapboxgl.Marker({
    element: el,
    anchor: "top"
  })
    .setLngLat(feature.geometry.coordinates)
    .addTo(map);

  // add to my own array in an object with a custom 'id' string from my geojson
  markersArray.push({
    id: feature.properties.id,
    marker
  });
});

这个id字符串可以是你想要的任何东西。如果您希望能够查询其他内容,甚至可以存储其他参数,例如纬度/经度:

markersArray.push({
  id: feature.properties.id,
  coordinates: feature.geometry.coordinates,
  marker
});

然后,如果我想访问标记的实例成员(如setDraggable),我可以使用Array.find()返回与markersArray中的搜索参数匹配的第一个实例:

let someIdQuery = "some-id";

let queriedMarkerObj = markersArray.find(
  marker => marker.id === someIdQuery
);
queriedMarkerObj.marker.setDraggable(true);

(请注意,Array.find()只返回数组中与您的条件匹配的第一个实例。如果您希望能够查询多个标记,请使用类似Array.filter()的内容。)

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