Copy data from JSON file to Vue2 Google Maps markers

I recently started working on a basic Vue project.

The project involves integrating a Google Map using the vue2-google-maps package.

Additionally, I have a JSON file (or data.php) containing the following information:

{
  "locations": [
    {
      "name": "Location 1",
      "address": "215 West Girard Avenue 19123",
      "location": {
        "lat": "39.9695601",
        "lng": "-75.1395161"
      },
      "label": "200",
      "preview": "img-1.png"
    },
    { ...

In the template section of the GoogleMap.vue file:

<template>  
    <div class="container">    
        <gmap-map id="map" v-bind="options">
            <gmap-marker
                :key="index"
                v-for="(m, index) in markers"
                :position="m.position"
                :clickable="true"
                :draggable="true"
                :label="m.label"
                @click="openWindow"

            />
            <gmap-info-window 
                @closeclick="window_open=false" 
                :opened="window_open" 
                :position="infowindow"
                :options="{
                  pixelOffset: {
                    width: 0,
                    height: 0
                  }
                }"
            >
                Hello world!
            </gmap-info-window> 
        </gmap-map>
    </div>  
</template>

Within the GoogleMap.vue script:

import { gmapApi } from "vue2-google-maps";

export default {
  name: "GoogleMap",
  data() {
    return {
      //map: null,
      options: {
        zoom: 12,
        center: {
          lat: 39.9995601,
          lng: -75.1395161
        },
        mapTypeId: "roadmap"
      },
      markers: [
        {
          label: "200",
          position: { lat: 39.9695601, lng: -75.1395161 }
        },
        {
          label: "30",
          position: { lat: 40.034038, lng: -75.145223 }
        },
        {
          label: "45",
          position: { lat: 39.9713524, lng: -75.159036 }
        }
      ],
      info_marker: null,
      infowindow: {
        lat: 39.9995601,
        lng: -75.1395161
      },
      window_open: false
    };
  },
  computed: {
    google: gmapApi
  },
  watch: {},
  methods: {
    initialize() {
      console.log("init");
    },
    openWindow() {
      console.log(this);
      this.window_open = true;
    }
  },
  mounted: function() {
    this.initialize();
  }
};

............................................................................................................................................................................................................

Question: What is the best way to populate the markers: [ { array with values from the data.php file (such as lat, lng, label)?

Answer №1

To import the JSON file, follow these steps:

import { default as locations } from '/path/to/json/file.json`

After importing, you can define a computed property named markers:

computed: {
  markers() {
    return locations.map(({ label, location: { lat, lon }}) => ({
     label,
     position: {
       lat: Number.parseFloat(lat),
       lng: Number.parseFloat(lon)
     }
    }))
  }
}

There are a couple of errors in the JSON file that need correction:

  • The key address is misspelled.
  • The key label is also misspelled.

Additionally, if using a php file, remember to utilize JSON.parse.

Access the Revised CodeSandbox here

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

Tips for triggering window load event on a particular page

I need to trigger the windows.load event on a specific page. Currently, I have set it up like this: $(window).load(function(){ if(document.URL == "/car-driving.html") { overlay.show(); overlay.appendTo(document.body); $('.popup' ...

What are the best practices for implementing optional chaining in object data while using JavaScript?

In my current project, I am extracting singlePost data from Redux and converting it into an array using Object.keys method. The issue arises when the rendering process is ongoing because the singlePost data is received with a delay. As a result, the initi ...

Implement a jQuery click event on a dynamically generated button in the code-behind

A button (Replybtn) is dynamically created when clicked in the code-behind file. --Default.aspx.cs-- protected void ReloadThePanelDetails_Click(object sender, EventArgs e) { litResultDetails.Text = litResultDetails.Text + "<button id='Replyb ...

Tips on making the form validation script operational

After developing a form alongside a form validation script to ensure that all fields are completed, the name and city sections only contain letters, while the age and phone sections solely include numbers, issues have arisen. It seems that despite the cons ...

Buttons in Datatables fail to appear when using ajax loading

I've been trying to solve this issue for a while now, but I just can't seem to figure it out. According to the documentation, adding initComplete should make the buttons appear, but I am still facing difficulties. Am I overlooking something? I&a ...

Obtaining response object when encountering 401 error in AngularJS

I am currently working with Angular 1.6.4, Express 4.15.2, and express-session. My goal is to identify whether a user is unauthorized to access a specific route by checking for the existence of the req.session.user parameter. If the user is not authorized, ...

The highlight_row function seems to be delayed, as it does not trigger on the initial onClick but works on subsequent clicks. How can I ensure it works properly right from the first click?

I developed an application using the Google JavaScript Maps API to calculate distances between addresses. I've encountered a bug where the row in the table is not highlighted on the first click, requiring a second click for the highlighting to take ef ...

What could be causing my React function to be declared but not utilized?

Struggling with my React project, I hit a roadblock when trying to import my generalInput file into my App file. The error message stated that the generalInput was declared but never read. Desperate for a solution, I even turned to AI for help, but it too ...

What is the method for displaying data from a JSON file that is associated with the wallet address of the authenticated user in next.js?

I am currently working on a claim page using next.js, where logged in Metamask addresses can perform the following tasks: Access data from a local .json file to check eligibility for claiming an item and display the claim page. Submitting a form to update ...

What methods can be employed to execute a intricate substitution utilizing both javascript and jQuery?

Within the source code of my web pages, I have elements that resemble the following: <div id="opt_3" >A)</div> <div id="opt_2" >B)</div> <div id="opt_4" >C)</div> <div id="opt_5" >D)</div> <div id="op ...

Experiencing difficulties when uploading information to an API in a React JS application

Trying to Send Data via React to Contact Form API Having issues trying to send input data through the API when clicking submit button. The error encountered is that the API call should look like this Example Link However, it calls in a different way Diff ...

Implementing div elements in a carousel of images

I've been working on an image slider that halts scrolling when the mouse hovers over it. However, I'd like to use div tags instead of image tags to create custom shapes within the slider using CSS. Does anyone have any advice on how to achieve th ...

MUI: Transforming the uncontrolled value state of Select into a controlled one with a new component

I'm attempting to develop an edit form for modifying data fetched from a database based on its ID. Here is what I have tried: import React, {FormEvent, useEffect, useState} from "react"; import TextField from "@material-ui/core/ ...

Inquiries about the jQuery Button Timer

Currently experimenting with jQuery to create a timer. Everything seems to be in place and the Stop Timer button is functioning properly. However, I'm facing issues with the Start Timer and Reset Timer buttons as they are not working as expected. Seek ...

Using AngularJS to refresh information stored in an array

My objective is to create a basic application that allows users to adjust their availability on weekdays. The code is functioning correctly as it retrieves data from the select box. However, I encounter an issue when trying to update Monday's data and ...

Leverage the power of v-model props in your Vue 3 component to efficiently retrieve API breakpoints

I am currently working on integrating the API breakpoints in my child component. These components are designed for my football web application. The breakpoints are sourced from: api-football My challenge lies in passing multiple prop values into a c ...

Can you explain the significance of the symbol '#' in a Vue Router URL?

I am wondering about the significance of the hash in Vue Router URL. I have noticed that by using mode: 'history', I can eliminate it from the URL. What are the practical differences between having the hash and not having it? ...

How to Safeguard an AJAX Service Request using jQuery and PHP (with a Session Token)

Currently, I am developing a framework where form submissions are handled through jQuery ajax calls to a .php service file. Here is a snippet of the jQuery code for reference: var dataSerialized = $(form).serialize(); var service = $(form).attr("action") ...

Implement a feature in JavaScript that highlights the current menu item

I'm currently developing a website at and have implemented a JavaScript feature to highlight the current menu item with an arrow. The issue I'm facing is that when users scroll through the page using the scrollbar instead of clicking on the men ...

What is the correct way to utilize Array.reduce with Typescript?

My current approach looks something like this: [].reduce<GenericType>( (acc, { value, status, time }) => { if (time) { return { ...acc, bestValue: valu ...