Exploring solutions for handling asynchronous issues with vue3-google-map

While working with a Vue library for managing Maps called vue3-google-map, I encountered an issue when trying to define certain polylines that would not allow me to select the center of the marked area:

Here is my map template:

 <template>
  <GoogleMap
    ref="mapRef"
    class="mimapa"
    :api-key="apiKey"
    :center="center"
    :zoom="16"
    :zoomControl="controls"
    :fullscreenControl="controls"
    :streetViewControl="controls"
  >
    <q-icon class="pin" :name="pin.icon" :size="pin.size" :color="pin.color" />
    <q-btn
      class="full-width btnMio"
      color="secondary"
      :label="btnLabel"
      @click="getLocation()"
      :disable="btnPosition"
      v-close-popup
    />
       <Polygon v-for="(zone, Index) in DeliveryZones" :key="Index" :options="zone"/>
  </GoogleMap>
  <div class="text-subtitle1 text-center">
    Locate your exact position on the map.
  </div>
</template>

This is my JavaScript code for the map

<script>
import { computed, defineComponent, ref, inject, onUpdated } from "vue";
import { GoogleMap, Polygon } from "vue3-google-map";
import { useGeolocation } from "../boot/useGeolocation";
import axios from 'axios'
var pointInPolygon = require('point-in-polygon');
export default defineComponent({
  name: "Map",
  components: { GoogleMap, Polygon },
  setup() {
    onUpdated(() => {
    // window.setTimeout(() => {
         setGeocerca() <------ HERE PROBLEM 
    // }, 3000); 
    })
    const mapPoint = inject('mapPoint')
    const { coords } = useGeolocation();
    const center = computed(() => ({
      lat: coords.value.latitude,
      lng: coords.value.longitude,
    }));
    const pin = ref(
      {
        color: 'secondary',
        icon: 'person_pin_circle',
        size: 'xl'
      }
    );
    const apiKey = ref('MY_API_KEY')
    const mapRef = ref();
    const controls = ref(false);
    const btnPosition = ref();
    const btnLabel = ref('Estoy Aquí...');
    const DeliveryZones =
    [
      {
        name: 'Zona1',
        strokeColor: "#00ff7a",
        strokeOpacity: 0.5,
        strokeWeight: 1,
        fillColor: "#00ff7a",
        fillOpacity: 0.05,
        price: 2,
        paths: [
        {lat: 10.3816643, lng:-66.9812285 },
        {lat: 10.3549424, lng:-66.9818722 },
        {lat: 10.3549002, lng:-66.9317471},
        {lat: 10.382213, lng:-66.9317471 },
        {lat: 10.3816643, lng:-66.9812285 },
        ]
      },
      {
        name: 'Zona2',
        strokeColor: "#ff0000",
        strokeOpacity: 0.5,
        strokeWeight: 1,
        fillColor: "#ff0000",
        fillOpacity: 0.05,
        price: 3,
        paths: [
          {lat: 10.38, lng:-66.98 },
          {lat: 10.35, lng:-66.99 },
          {lat: 10.36, lng:-66.93},
          {lat: 10.37, lng:-66.95},
          {lat: 10.38, lng:-66.98 },
        ]
      }

    ]
    let centerCurrent = null;
    let tarifa = null;
    function setPoligonToArray(poligon){
       let arreglo = []
       let arr=[]
       for (let cords of poligon){
         arr = [cords.lat, cords.lng]
         arreglo.push(arr)
       }
       return arreglo
    }
    let prueba = 0
    function setGeocerca() {

      if(mapRef.value.ready) {
       mapRef.value.map.addListener("center_changed",() => {
       let activo = 0
       for (const zone of DeliveryZones) {
        const selectedPoint = [mapRef.value.map.getCenter().lat(), mapRef.value.map.getCenter().lng()]
       if(pointInPolygon(selectedPoint, setPoligonToArray(zone.paths)) === true)
         {
           activo++
         }
       }
       if(activo > 0) {
        btnPosition.value = false
        btnLabel.value = "Estoy Aquí..."
        pin.value = {
          color: 'secondary',
          icon: 'person_pin_circle',
          size: 'xl'
          }
       }else {
        btnPosition.value = true
        btnLabel.value = "Delivery no disponible para esta zona"
        pin.value = {
          color: 'primary',
          icon: 'location_off',
          size: 'xl'
          }
       }
      });
     }else{
       console.log('Afuera' + prueba)
     }
    }
    function getLocation() {
      if (mapRef.value.ready) {

        // mapPoint.value = mapRef.value.map.getCenter();

       const selectedPoint = [mapRef.value.map.getCenter().lat(), mapRef.value.map.getCenter().lng()]
       for (const zone of DeliveryZones) {
         if(pointInPolygon(selectedPoint, setPoligonToArray(zone.paths)) === true)
         {
           tarifa = zone.price;
           console.log(tarifa)
         }
          console.log(zone.name + ' = '+ pointInPolygon(selectedPoint, setPoligonToArray(zone.paths))); // true
       }
      const mapQuery = "https://maps.googleapis.com/maps/api/geocode/json?latlng="+selectedPoint+"&key=" + apiKey.value
      console.log(mapQuery)
      axios.get(mapQuery).then((result) => {
        mapPoint.value = result.data.results[3].formatted_address;
      })
      }
    }
    
    return { center, getLocation, mapRef, controls, mapPoint, DeliveryZones, btnPosition, btnLabel, pin, apiKey};
  },
});
</script>

onUpdated(() => { // window.setTimeout(() => { setGeocerca() <------ HERE THE PROBLEM IS JUST THIS FUNCTION DOES NOT WAIT FOR THE MAP TO LOAD AND GIVE ERROR THAT THE MAP REF OBJECT DOES NOT EXIST, OF COURSE IF I ACTIVATE THE TIMEOUT IT WORKS BUT IF THE LOAD TIME OF THE MAPREF COMPONENT IS GREATER THAN 3000 THE ERROR COMES BACK. // }, 3000); })

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be causing Jquery to alter data while making an ajax Post request?

My situation involves an object that has the following structure: var data = { "to" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="83f0eceee6ecede6c3e2e1e0ade0ecee">[email protected]</a>", "attachment" : [ ...

Exploring ways to retrieve data prior to mounting in Vue.js

Imagine I had the following HTML structure: <div id="app" data-user="testing"></div> Once I mount the Vue app on #app, it changes to this: <div data-app="true" class="v-application v-application--is-ltr theme--light" id="app"> What is ...

Let's explore further - delving into JSON & array manipulation using the foreach loop in Pure JavaScript

Although I have some experience with Java Script, I still consider myself a beginner in certain areas, particularly when it comes to accessing JSON objects and arrays. I've tried various syntax and options for accessing arrays using [], but so far, I ...

Leveraging req.files for uploading multiple files at once

When it comes to handling a multiple file upload on the client side, I have encountered an issue with my HTML code. Here is what it looks like: form(method='post', enctype='multipart/form-data')#createReportForm input(type='file ...

Learn how to dynamically incorporate multiple Bootstrap collapse elements in PHP

I've encountered an issue with my code that contains both HTML and PHP. The problem arises when there are multiple elements in a collapse, as only the first element works properly. This is due to the fact that each element has the same id named "colla ...

Exploring ways to retrieve texture dimensions using Three.js

Can someone please advise me on how to retrieve the dimensions of a texture? I have set my texture using the following line of code: const texture = THREE.ImageUtils.loadTexture(src) Do I need to load the image in order to obtain its dimensions (and can ...

"Exploring the process of looping through a JSON object following an asynchronous retrieval of JSON data using

I am facing an issue while trying to iterate through a JSON object in jQuery after fetching it asynchronously. I have a function called 'listFiles' that uses async to successfully retrieve a file list from a directory (dir) by calling an API endp ...

Vue2 - Dealing with Unresponsive Bootstrap Popover Content

I have been working on developing a popover component using Bootstrap4 in Vue framework: <template> <div> <div :id="uid + '_Content'" class="d-none"> <slot name="content"& ...

Modify the hyperlink address in the body of the webpage using jQuery

I'm searching for a solution to modify the href attribute in the following code: <link rel="stylesheet" type="text/css" href="theme1.css"> For instance, changing it from: <link rel="stylesheet" type="text/css" href="theme1.css"> to: & ...

Utilizing withRouter outside a component to navigate through historical data

I'm still getting the hang of react router and encountering some challenges. I can easily use history within a component without any issues. However, when trying to access history from a function outside the component, I run into problems. Despite my ...

Trouble activating header checkbox on initial click

Hello everyone, I have a question about two views: 1- Index 2- Edit In my grid, the header has a single checkbox. When I try to click the checkbox to select all rows, it doesn't work properly. The first time I click to uncheck and then check it agai ...

Is it possible to utilize a single command in Discord.js to send multiple embeds?

Is there a way to create a unique bot in Node.js (using Discord.js) by utilizing Visual Studio Code? This exceptional bot should be capable of responding with various embed messages when given one specific command. I attempted using command handler, but u ...

Getting the chosen value from a dropdown menu on form submission using PHP

How to Populate a Combo Box from a Database in PHP? <td>Item Name:</td> <td><select name="items"> <option value="0" selected="selected"> Choose</option> <?php while($row = mysql_fetch_ass ...

What is the best way to connect with the <progress> element?

Vuex.Store({ state: { percentage: 0, }, ... I'm attempting to use the code <progress max="100" v-model="percentage"></progress>, but I keep encountering the error message 'v-model' directives are not supported on <pro ...

Is there a way to consistently trigger the browser.webRequest.onBeforeRequest event in Mozilla Firefox when it is launched via a link?

Hello knowledgeable individuals. I am unable to solve this issue on my own. Here is the add-on I have created: 1) manifest.json: { "manifest_version": 2, "name": "Example", "version": "1.0", "description": "Example", "permissions": [ "tabs" ...

Ways to clear dropdown selection in Vue based on a specific condition?

I am currently developing a dropdown menu for selecting visit status options, which include "pending," "canceled," "rejected," and "approved." In the case of an approved visit status, I would like the dropdown selection to only display the options for "can ...

I am unable to apply CSS to style my <div> element

I've run into a snag with my coding project, specifically when attempting to style my div. Here is the code I have so far: All CSS rules are applying correctly except for the .chat rule. Can someone help me figure out what I'm doing wrong? var ...

Ways to acquire ttf files from a third-party domain without encountering CORS issues

I am attempting to obtain a .ttf file from an external website for use in my web application. However, when I try the following code: @font-face { font-family: 'font'; src: url('http://xxx.xyz/resources/tipografias/font.ttf') forma ...

How can I insert a item into an Array using JavaScript code?

My instructor set up an array in my JavaScript file that is off limits for me to modify. My task is to add new objects to it through code without directly manipulating the existing array. Here's a snapshot of what my array contains: const words = [{ ...

Error encountered in React JS: The property being accessed is undefined and therefore cannot be mapped

I have been working on a MERN project and I am currently at the stage where I am integrating the frontend and backend using Axios. However, I have encountered some issues. One of the most common errors I am facing in my list screens is: TypeError: Cannot r ...