DEV Community

John Michael Biddulph
John Michael Biddulph

Posted on

@click to a method in Nuxt using mapbox in a popup

I am using MapBox in my NUXT 3 project. In my code, I have 2 popups. I am trying to call a method openDrawer to log something to the console, this doesn't seem to be working?! please help

<script setup>
import { ref, onMounted, reactive } from 'vue';
import mapboxgl from 'mapbox-gl';

const accessToken = ref("");
const map = ref(null);
const drawer = ref(false);
const markers = reactive({}); // Reactive object to store marker information

onMounted(() => {
  createMap();
  addMarkers();
});

const createMap = () => {
  accessToken.value = "xxxxxxxxxx";
  mapboxgl.accessToken = accessToken.value;
  map.value = new mapboxgl.Map({
    container: "map",
    style: "mapbox://styles/mapbox/light-v11",
    zoom: 11,
    center: [107.61861, -6.90389],
  });
}

const addMarkers = () => {
  const markerData = [
    { id: 1, lngLat: [107.61861, -6.90389], popupContent: 'Marker 1' },
    { id: 2, lngLat: [107.62, -6.9], popupContent: 'Marker 2' },
    // Add more marker data as needed
  ];

  markerData.forEach(data => {
    const { id, lngLat, popupContent } = data;

    // Create a marker
    const marker = new mapboxgl.Marker()
      .setLngLat(lngLat)
      .addTo(map.value);

    // Create a popup for each marker
    const popup = new mapboxgl.Popup({ offset: 25 })
      .setHTML(`
        <h3>${popupContent}</h3>
        <p>This is a popup.</p>
        <button @click="openDrawer(id)">Click me!</button>
      `);

    // Add a popup to the marker
    marker.setPopup(popup);

    // Store marker information in the reactive object
    markers[id] = { marker, lngLat, popupContent };
  });
}

const openDrawer = (markerId) => {
  // Use markers[markerId] to access information about the clicked marker
  const clickedMarker = markers[markerId];
  drawer.value = !drawer.value;
  console.log('Clicked Marker Information:', clickedMarker);
}
</script>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)