Reputation: 3
I would like to add id to Marker(), but it's showing the error Property 'id' does not exist on type 'Marker'.
There is a way how to add an id to non-existent property??
Here is my code....
const maps = useRef<mapboxgl.Map | null>(null);
const markers = useRef<any>({}); // for the moment is any
useEffect(() => {
maps.current?.on('click', (ev: mapboxgl.MapMouseEvent & mapboxgl.EventData) => {
const { lng, lat } = ev.lngLat;
const marker = new mapboxgl.Marker();
marker.id = uuidV4(); // id' does not exist on type 'Marker
marker.setLngLat([lng, lat]).addTo(maps.current!).setDraggable(true);
markers.current[marker.id] = marker; // id' does not exist on type 'Marker
});
}, []);
I am new to typescript so, I'll be happy to get a tips and solution. Thank you.
Upvotes: 0
Views: 1131
Reputation: 31
You can also set it on the getElement()
method which returns the DOM element to use as a marker. The default is a light blue, droplet-shaped SVG marker.
marker.getElement().id = uuidV4();
marker.setLngLat([lng, lat]).addTo(map.current!).setDraggable(true);
markers.current[marker.getElement().id] = marker;
Upvotes: 0
Reputation: 42160
You can define your own type that extends the mapbox marker type and adds an id
property.
type MarkerWithId = mapboxgl.Marker & {id: string}
Your markers
ref is a dictionary of these objects.
const markers = useRef<Record<string, MarkerWithId>>({});
When you call new mapboxgl.Marker()
you get a marker without an id
, so you need to use a type assertion.
const marker = new mapboxgl.Marker() as MarkerWithId;
The rest should be fine!
Upvotes: 2