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

Using Vue.js within Cordova platform allows developers to create dynamic

Having trouble integrating a Vue.js app into Cordova. Everything seems to be working fine, except I'm unsure how to capture Cordova events (deviceready, pause, etc.) within my Vue application. Using the Webpack template from vue-cli. This is my file ...

MongooseError: The operation `users.findOne()` has encountered an issue

While working on my movie website, I encountered an issue when setting up the login feature. When trying to register using POST through Insomnia, I received an error message stating "MongooseError: Operation users.findOne() buffering timed out after 10000m ...

The Node.js Express server does not provide access to certain static files

I am currently utilizing the angularjs-gulp-browserify-boilerplate for my development environment on Windows 10. Once I run gulp in dev mode, static files are moved to the build directory: ./build |_js |_css |_img |_fonts |_lang In additio ...

Ensure that the Observable is properly declared for the item list

.html // based on the error message, the issue seems to be in the HTML code <ion-card *ngFor="let invitedEvent of invitedEvents"> <ion-card-content> <img [src]="eventPhotoUrl$[invitedEvent.id] | async"> </ion ...

Vue.js displaying incorrectly on Windows Server 2019 IIS post deployment

Once I run npm serve, everything runs smoothly. However, when I deploy my app with an API in an ASP.NET application, it doesn't scale properly. I am using Router and History for navigation. Anonymous user authentication is enabled and static content h ...

The 'gulp-jade' plugin seems to be malfunctioning and failing to properly compile jade files into HTML documents

Currently, I am immersed in a project where I rely on using gulp. My main objective is to compile the jade files I create (found in the _jadefiles folder) and have them output as .html files in the _includes folder within my project. The current list of t ...

Eliminating the impact of a CSS selector

I have a complex mark-up structure with multiple CSS classes associated: classA, classB, classC, classD. These classes are used for both styling via CSS and event binding using jQuery selectors. The Challenge: I need the jQuery events to be functional whi ...

Unable to deserialize an instance of java.util.List from the VALUE_STRING

In the process of developing a new application, my goal is to send data to a server and receive a response in a specific format. Here's an example of how the format should look: { "userName" :"<a href="/cdn-cgi/l/email-protection" class="__cf_e ...

Updating the content of a list item on the fly using React

After spending all day on this, I am feeling a bit frazzled. Trying to achieve what would take 20 seconds in JQuery has proven to be quite the challenge in React ¯\_(ツ)_/¯ In my application, tags are ranked by importance from 1 to 9. Simple enoug ...

JavaScript encounters a parsing error when dealing with an async function

Ever since I developed a node.js web application, I've been utilizing MSSQL for the database. To streamline SQL functions, I crafted functions (sql.js) to handle all the necessary queries. Furthermore, I set up async function handlers (controllers.js) ...

Here's a guide on using a button to toggle the display of password value in Angular, allowing users to easily hide

I have successfully implemented an Angular Directive to toggle the visibility of password fields in a form. However, I am facing an issue with updating the text displayed on the button based on the state of the input field. Is there a way for me to dynami ...

Can the selected week be highlighted along with the corresponding week number in a row?

Can we display the number of the week in a row along with the selected week, either in the toolbar or somewhere else? I attempted to utilize ToolbarComponent, but it overrides the entire header. However, I would like to keep it as is and just add informat ...

Troubleshooting: Addressing the Issue of "Missing Product Attribute on Search Results"

Running into an issue while trying to map over a graphql query using an imported component. The data connection is set up correctly but encountering a problem with passing the data, resulting in the error message Missing product attribute on result. After ...

Troubleshooting the Issue of Table Append not Functioning in Live Environment

I'm currently in the process of developing a website using Bootstrap, and I'm facing an issue where one of the tables gets cleared out and updated with new data when a button is clicked. This functionality works perfectly fine during testing on V ...

Tips for setting up a typeorm entity with attention to its nullable fields

How can I assign values to typeorm entities and insert them into the database? import { PricingPatternElement } from file const Element:PricingPatternElement = { displayOrder: 10, elementName: "test", createdAt : getCurrentDate(), createdBy: &qu ...

What is the method for obtaining the viewModel in a Knockout component?

I need to prepopulate a knockout component when the document is ready. This is the code I have written: function Finding(id, trigger) { var self = this; self.id = ko.observable(id); self.trigger = ko.observable(trigger); } function FindingVi ...

Display outcomes for chosen checkboxes

When I call the API: $url = 'https://plapi.ecomexpress.in/track_me/api/mawbd/?awb=awbnumber&order=' . $orderrecords[$k]["order_id"] . '&username=admin&password=admin123';, I retrieve the status results of all Order IDs and d ...

Passing data from the server to the HTML page for manipulation

I need assistance in retrieving and manipulating the value stored in the variable $result[] from a PHP file to my HTML file for further processing. Can you provide guidance or reference code on how to return data from server side to client side? Here is a ...

Validate user credentials using both jQuery and PHP to display an error message if login details are incorrect

Working on a form validation using jQuery and PHP. I am utilizing an .ajax request to the server in order to verify if data has been entered into the form, and execute different actions based on the callback response received from the server. For instance, ...

Is it possible to display a value conditionally based on a condition from a Json object?

I'm looking to add a new feature that displays all the movies featuring Sean Connery in a button, but I'm stuck on how to implement it. Prettier 2.7.1 --parser babel </pre> Input: import React, { useState } from "react"; import ...