Having troubles with Vue.js lifecycle events? Are you experiencing issues with your data array only being populated after refreshing the page with a Webpack loader? Struggling to get Google Maps

Just dipping my toes into vueJS, currently working on an app that can plot locations on a google maps element. My code may be messy, but it's all part of the learning process for me. Any assistance is greatly appreciated.

Context

I have an array of geese objects:

[
    {
        "id": 74,
        "created_at": "Jan 14 08:24:46 PM",
        "latitude": "<a coord near me>",
        "longitude": "<a coord near me>"
    },
    {
        "id": 73,
        "created_at": "Jan 14 06:56:33 PM",
        "latitude": "<a coord near me>",
        "longitude": "<a coord near me>"
    }
]

Objective

The goal is to transform this array of geese objects into another array of markers, each containing only lat/long values, which I can then pass into google maps to display markers.

Challenges

The map itself displays properly, and obtaining the current location while centering works as intended.

Strangely, the markers array doesn't populate correctly upon initial page load. It only fills up when the webpack loader reloads the element or triggers within the "getMarkers()" method. Despite examining vue's lifecycle documentation, I haven't been able to rectify this issue.

Furthermore, even when the markers load successfully (verified through vue devtools chrome extension), they still fail to appear as markers in the application (although manual input of mock coordinates via vue devtools shows them).

My Code

<template>
  <div>
    <gmap-map :center="this.center" :zoom="15" style="width:100%;  height: 400px;">
      <gmap-marker
        :key="index"
        v-for="(m, index) in markers"
        :position="m.position"
      ></gmap-marker>
    </gmap-map>
  </div>
</template>
<script>
export default {
  name: "GoogleMap",
  props: {
    geese: Array
  },
  data() {
    return {
      markers: [],
      center: {}
    };
  },
  methods: {
    geolocate() {
      navigator.geolocation.getCurrentPosition(position => {
        this.center = {
          lat: position.coords.latitude,
          lng: position.coords.longitude
        };
      });
    },
    getMarkers() {
      console.log("in getMarkers")
      for (var goose of this.geese) {
        console.log("got into for loop of geese")
        console.log("dsdfss")
        const marker = {
          lat: parseFloat(goose.latitude),
          lng: parseFloat(goose.longitude)
        };
        this.markers.push({ position: marker });
      }
    }
  },
  mounted() {
    this.geolocate();
    this.getMarkers()
  }
};
</script>

Once again, thank you for any guidance provided.

Answer №1

Resolved the problem!

This is how my mounted code appears:

mounted() {
  document.onreadystatechange = () => {
     if (document.readyState == "complete") {
       console.log('Page loaded successfully')
       this.fetchData()
     }
   }
}

I also included "this.fetchLocation()" in the created method.

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

Utilizing class-validator for conditional validation failure

Implementing conditional validation in the class-validator library using the given example, I need to ensure that validation fails if the woodScrews property is assigned a value when the tool property is set to Tool.TapeMeasure. I've searched extensiv ...

What is the best way to transfer an ID to a dropdown selection list?

Whenever a user chooses an option from a drop-down menu, an event needs to be triggered. I have a checkbox that retrieves an ID from the database; based on this ID, a user can be added or removed from the drop-down menu. var ajReq = new XMLHttpRequest(); ...

Error: The checkbox property 'checked' is read-only and cannot be assigned to

After applying a filter to the following checkboxes, I noticed that once the filter is removed, the checkboxes disappear. The reason for this behavior is clear to me. However, the issue arises when attempting to assign the checked value to my ng-model in A ...

Enhance the appearance of Ionic popups

Can someone help me with resizing a pop up? I've been struggling to get it right. This is the popup template in question: <ion-view> <ion-content scroll="false" class=""> test </ion-content> < ...

Is it possible to load a JS file without using the require function?

Is there a method to load a JavaScript file without using require, but with fs for instance? I am aware that for JSON files I can utilize: const jsonFile = JSON.parse(fs.readFileSync("/jsonfile.json")) Can the same be done for a JavaScript file? I am inq ...

Tips for arranging cards in a stacked position: To create a visually

I'm currently developing a project using react typescript, and I need to showcase various projects in the form of cards. However, I would like these cards to be displayed in a stacked layout like this Here is the component for displaying the projects ...

Utilizing CSS to showcase various sections of a webpage

Here is a basic example of an HTML file available at this link: http://jsfiddle.net/WhupP/2/ The webpage consists of 4 main sections - header, left-column, righ-column, and footer. Additionally, there are 2 @media elements named screen and print. When att ...

What could have caused my javascript file to disappear from npm?

After creating a small library consisting of a .js file with commonly used functions, I placed it in the node_modules directory alongside my other packages. Everything seemed to be going well. A few days later, I decided to add a new package using npm ins ...

DJs communicating by sharing attachments independently of embedding them

I want my message to look like this, but when using interaction.reply it shows up as this. This is the code I'm using: fs.readdir("./images", (error, files) => { if (error) return console.log(error) const num = (Math.floor(Math.random() ...

How can you use JQuery to assign a single function as an onClick handler for multiple radio buttons?

I have a custom function named handleOnClickRadio(i, j);, and multiple radio buttons with the IDs in the format of id="something-radio[i][j]". These radio buttons are all contained within a table labeled "bigtable". Is there a way to link the function han ...

Struggling with sending form data to the back end when uploading images in Angular

I've been facing a challenge trying to implement profile picture upload alongside standard text data and sending it all to the backend to create a new user through mongoose. Despite my efforts, using tools like ng-file-upload/angular-file-upload and e ...

What is the process for sending an HTTP post request with a React/Typescript frontend and a C#/.Net backend?

In the frontend code, there is a user login form that accepts the strings email and password. Using MobX State Management in the userstore, there is an action triggered when the user clicks the login button to submit the strings via HTTP post. @action logi ...

When accessing the innerHTML and outerHTML properties on an HTMLElement, they may return undefined without triggering

Task: My goal is to take an HTML string, make changes to certain attributes of image tags within it, and then return the modified HTML string. The function I have developed follows these steps: private resolveImagesInHTML (body: string): string { le ...

The webpage is completely blank, displaying only a stark white screen

After designing a website, I encountered an issue where upon opening it in the browser, it only shows a blank white page. I am puzzled as to why this is happening. Could you please take a look at this link and assist me? Thank you in advance. ...

Traverse through nested nodes using GraphQL in Nuxt

I've been encountering some challenges with Apollo, GraphQL, and Nuxt. I'm not sure if it's specifically related to Nuxt or Vue. I'm attempting to utilize WordPress as a headless CMS via the WP-GraphQL plugin. Here is my query: WP-Gra ...

Facing issues with vertical Tab display in Bootstrap using Vue.js - unexpected results

Below is the script I am working with: <vue-tabs class="row" direction="vertical" value="Description"> <div v-for="(siteParts, index) in sitePartLine"> <v-tab :title="sitePartLine[index].serial_no" v-if="sitePartLine[i ...

Upon making an axios get request to localhost:4000/, the responseUrl redirects to localhost/ which leads to a 404 error

When enhancing a server extension on an already existing same-server backend, I encountered some issues: import server from 'myserver'; import { verifyJwt } from 'jwt.middleware'; import axios from 'axios'; const app = server ...

Is it possible to achieve consistent scrollY height values across various screen sizes?

Looking to apply a class when a certain screen height is reached? Here's my approach: window.onscroll = function() {scrollPost()}; function scrollPost () { var x = window.screen.width; var i = window.scrollY; var a = i / x; animator ...

Having trouble displaying Vue Toast messages?

I have been trying to incorporate a toast message into my code, but unfortunately, the message does not appear and there are no errors in the console. The code functions properly and the invitation is sent successfully. I have used similar code in other fi ...

Is there a way to create a function in JavaScript that eliminates duplicate Objects within an Array of Objects?

Currently, I'm working on a function to store details of a couch in a JS object with 3 properties locally. The properties include: An ID (obtained from the product URL using a function) A color (retrieved through an event listener) A quantity ...