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

时间:2017-06-21 16:13:45

标签: geolocation mapbox mapbox-gl-js

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

我尝试听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
            }
        });
    });
});

1 个答案:

答案 0 :(得分:1)

geolocate事件实际上与geolocate对象绑定在一起,而不是地图对象

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