如何使用 mapboxgl.GeolocateControl 将标记添加到 mapbox

How to add marker to mapbox using mapboxgl.GeolocateControl

我想在用户定位后添加一个标记。

我尝试收听地理定位事件,但未添加任何标记。 我该如何进行?

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

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

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