我创建了一个mapbox图层来添加自定义图钉。它将图钉添加到我的地图。但是,当我将onClick事件附加到此层时,map.getLayer('custom-pins')始终返回未定义的
。export const drawCustomPinsToMap = (map: mapboxgl.Map, pin:
IPinJson) => {
const userGeolocationLayer = map.getLayer('user-geolocation-
shadow');
const userGeolocationLayerId = userGeolocationLayer &&
userGeolocationLayer.id;
const { iconUrl, iconSize } = pin;
map.loadImage(iconUrl, (error: string, image: HTMLImageElement) =>
{
if (error) throw error;
map.addImage('custom-pin', image);
map.addLayer(
{
id: 'custom-pins',
type: 'symbol',
interactive: true,
source: 'pins-and-clusters',
filter: ['!has', 'point_count'],
layout: {
'icon-image': 'custom-pin',
'icon-size': iconSize
}
},
userGeolocationLayerId
);
});
};
export const bindPinsClickHandlers = (
map: mapboxgl.Map,
handleLocationClick: (slug: string) => void,
layerId: string
) => {
if (map.getLayer(layerId)) {
map.on('click', layerId, (event: any) => {
if (!deviceMatch('phablet')) {
map.flyTo({
center: event.features[0].geometry.coordinates,
zoom: 16
});
}
handleLocationClick(event.features[0].properties.slug);
});
map.on('mouseenter', layerId, () => {
map.getCanvas().style.cursor = 'pointer';
});
map.on('mouseleave', layerId, () => {
map.getCanvas().style.cursor = '';
});
}
};
layerId被定义并返回期望的layerId,“ custom-pins”。 但是map.getLayer('custom-pins')返回未定义,因此未附加onClick事件。
关于我在这里缺少什么的任何想法?
答案 0 :(得分:1)
弄清楚了-这是一个异步问题。 map.loadImage是异步的,因此必须包装在Promise中。