【问题标题】:How to add marker to mapbox using mapboxgl.GeolocateControl如何使用 mapboxgl.GeolocateControl 向 mapbox 添加标记
【发布时间】:2017-06-21 16:13:44
【问题描述】:

我想在用户找到自己之后添加一个标记。

我尝试收听 geolocate 事件,但没有添加任何标记。 我应该怎么做?

map.addControl(new mapboxgl.GeolocateControl({
    positionOptions: {
        enableHighAccuracy: true,
        watchPosition: true
    }
}));
map.on('geolocate ', () => {
    map.loadImage('images/pin2.png', (error, image, data) => {
        if (error) throw error;
        console.log(data);
        map.addImage('pin2', image);
        map.addLayer({
            "id": "points",
            "type": "symbol",
            "source": {
                "type": "geojson",
                "data": {
                    "type": "FeatureCollection",
                    "features": [{
                        "type": "Feature",
                        "geometry": {
                            "type": "Point",
                            "coordinates": [data.position]
                        }
                    }]
                }
            },
            "layout": {
                "icon-image": "pin2",
                "icon-size": 1
            }
        });
    });
});

【问题讨论】:

  • 首先确定问题是地理定位控件未触发,还是标记不可见,或者两者兼而有之。那么-如果您将代码移动到on(load...),标记会显示吗?

标签: geolocation mapbox mapbox-gl-js


【解决方案1】:

地理定位事件实际上是与地理定位对象而不是地图对象绑定在一起的

let geolocate = new mapboxgl.GeolocateControl({
    positionOptions: {
        enableHighAccuracy: true,
        watchPosition: true
    }
});

map.addControl(geolocate);

geolocate.on('geolocate', (e) => {
    map.loadImage('https://upload.wikimedia.org/wikipedia/commons/thumb/6/60/Cat_silhouette.svg/400px-Cat_silhouette.svg.png', (error, image) => {
        console.log(e)
        if (error) throw error;
        map.addImage('cat', image);
        map.addLayer({
            "id": "points",
            "type": "symbol",
            "source": {
                "type": "geojson",
                "data": {
                    "type": "FeatureCollection",
                    "features": [{
                        "type": "Feature",
                        "geometry": {
                            "type": "Point",
                            "coordinates": [e.coords.longitude, e.coords.latitude]
                        }
                    }]
                }
            },
            "layout": {
                "icon-image": "cat",
                "icon-size": 0.3
            }
        });
    });
});

看看工作的JSbin

【讨论】:

  • 请注意,浏览器中的地理位置仅适用于 https 域。当连接不安全时,您将不会在地图上看到 Geolocate 控件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-26
  • 2021-10-21
  • 1970-01-01
  • 2016-05-16
相关资源
最近更新 更多