svelte-mapbox
svelte-mapbox copied to clipboard
Event dispatching from <Marker /> elements
Hi,
I can't seem to add eventhandlers for Marker components whereas for the Map component it works just fine. Am I missing something? Simplified pseudocode:
<script>
...
let showPanel;
const onMapReady = () => {
// This DOES get called
};
const onMarkerReady = () => {
// But this NOT
};
const handleClick = () => {
showPanel = !showPanel; // Does NOT get called
};
<script>
<section>
{#await getMarkerData()}
Loading...
{:then markers}
<Map
accessToken="..."
style="mapbox://styles/mapbox/satellite-v9"
zoom="6"
{center}
bind:this={mapComponent}
on:ready={onMapReady}>
{#if markers}
{#each markers as marker}
<Marker lat={marker.lat} lng={marker.lng} label={marker.label} on:ready={onMarkerReady} on:click={handleClick} />
{/each}
{/if}
</Map>
{/await}
</section>
The marker component doesn't have any event handlers registered. It probably needs a PR to add this :)
Just put button
into Marker slot
<Marker>
<button on:click></button>
</Marker>
After reading the mapbox api documentation I edited Marker.svelte to expose a click event handler but I also suggest this should be changed in Marker.svelte, not with a slotted helper button.
See markerel and the on:click on the first div:
Marker.svelte
<script>
import { onMount, getContext } from 'svelte'
import { contextKey } from '../mapbox.js'
const { getMap, getMapbox } = getContext(contextKey)
const map = getMap()
const mapbox = getMapbox()
function randomColour () {
return Math.round(Math.random() * 255)
}
function move (lng, lat) {
marker.setLngLat({ lng, lat })
}
export let lat
export let lng
export let label = 'Marker'
export let popupClassName = 'beyonk-mapbox-popup'
export let markerOffset = [ 0, 0 ]
export let popupOffset = 10
export let color = randomColour()
export let popup = true
export let popupOptions = {}
export let markerOptions = {}
let marker
let element
let elementPopup
let markerel
$: marker && move(lng, lat)
onMount(() => {
const namedParams = Object.assign(
{
offset: markerOffset
},
element.hasChildNodes() ? { element } : { color }
)
marker = new mapbox.Marker(Object.assign(namedParams, markerOptions))
markerel = marker.getElement()
markerel.addEventListener('click', (e) => {
map.flyTo({center: [lng,lat],essential:true})
})
if (popup) {
const namedPopupParams = { offset: popupOffset, className: popupClassName }
const popupEl = new mapbox.Popup(Object.assign(namedPopupParams, popupOptions))
if (elementPopup.hasChildNodes()) {
popupEl.setDOMContent(elementPopup)
} else {
popupEl.setText(label)
}
marker.setPopup(popupEl)
}
marker
.setLngLat({ lng, lat })
.addTo(map)
return () => marker.remove()
})
export function getMarker () {
return marker
}
</script>
<div on:click bind:this={element} >
<slot/>
</div>
<div class='popup' bind:this={elementPopup} >
<slot name="popup" />
</div>