mapbox / mapbox-gl-js

Interactive, thoroughly customizable maps in the browser, powered by vector tiles and WebGL
https://docs.mapbox.com/mapbox-gl-js/
Other
11.09k stars 2.21k forks source link

Wait for marker image load #12931

Open b3n3w opened 11 months ago

b3n3w commented 11 months ago

mapbox-gl-js version: latest

Question

Hi there !

i'm currently trying to get custom marker images to work in Svelte. It seems that sometimes (on refresh) the marker icons shows up and sometimes not, which is why i guess it could be loading issue.

This is my CustomMarker Component:

<script lang="ts">
    import { onMount } from "svelte";
    import mapboxgl from "mapbox-gl";

    export let marker: any;
    export let map: any;

    onMount(() => {
        const markerElement = document.createElement("div");
        markerElement.className = "custom-marker";

        new mapboxgl.Marker(markerElement)
            .setLngLat(marker.geometry.coordinates)
            .setPopup(
                new mapboxgl.Popup({ offset: 25 }).setHTML(
                    `<h3>${marker.properties.message}</h3><p>Test description</p>`
                )
            )
            .addTo(map);
    });
</script>

<style>
    .custom-marker {
        background-image: 'url("https://aqhnreobugwxvsogdiox.supabase.co/storage/v1/object/public/Images/example.png")';
        background-size: cover;
        cursor: pointer;
        width: 30px;
        height: 30px;
    }
</style>

And this is how i add the markers on the map page:

 <div class="map" bind:this={mapContainer} />
    {#each markers.features as marker}
        {#if marker.geometry.type === "Point"}
            <MarkerComponent {map} {marker} />
        {/if}
    {/each}

When i remove the markerElement from the new mapboxgl.Marker the default marker can be shown and clicked.

Links to related documentation

I used this as an starting point:

https://docs.mapbox.com/help/tutorials/use-mapbox-gl-js-with-svelte/

3zzy commented 9 months ago

This is appropriate for Stack Overflow as it's a question, not an issue. To quickly answer it, I believe you may need to enclose your marker creation within the map's 'load' event.