首页 > 解决方案 > Vue警告]:渲染错误:“TypeError:无法读取未定义的属性'map'”Vue Google maps

问题描述

我有一个简单的 vue 项目,它从我的 API 调用数据。

有一个谷歌地图,我需要连接并显示通过 API 从数据库中检索的 lat 和 long 的标记。

我已经为 vue 启用了 Axios,但是 axios 函数给了我一个错误。

vue.runtime.esm.js?2b0e:619 [Vue 警告]:渲染错误:“TypeError:无法读取未定义的属性 'map'”

文件:GoogleMap.vue

<template>
  <div>
    <div>
      <h2>Search and add a pin</h2>
    </div>
    <br/>
    <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>
import axios from "axios";
import { gmapApi } from "vue2-google-maps";
export default {
  name: "GoogleMap",
  data() {
    return {
      // maps - entry point
      options: {
        zoom: 12,
        center: {
          lat: 6.9271,
          long: 79.8612,
        },
        mapTypeId: "roadmap",
      },
      info_marker: null,
      infowindow: {
        lat: 39.9995601,
        long: -75.1395161,
      },
      window_open: false,
    };
  },
  mounted() {
    this.initialize();
    let config = {
      method: "get",
      url: "http://127.0.0.1:8002/api/locations/",
    };
    axios(config).then((val) => {
      this.Data = val.data;
    });
  },
  computed: {
    google: gmapApi,
    markers() {
      return this.Data.map(
        (locationName, lat, long) => ({
          locationName,
          position: lat,
          long: long,
        }));
    },
  },
  watch: {},
  methods: {
    initialize() {
      console.log("init");
    },
    openWindow() {
      console.log(this);
      this.window_open = true;
    },
  },
};

API端点:

[
{
"id": 1,
"nic": "9886556V",
"locationName": "Cargils",
"lat": "6.5945719",
"long": "79.9489557",
"policeArea": "south",
"dateTime": "2021-04-20T04:26:49.000000Z",
"created_at": null,
"updated_at": null
},
{
"id": 2,
"nic": "123456789V",
"locationName": "Super Centre",
"lat": "6.9175873",
"long": "79.8589105",
"policeArea": "Hyde Park Corner",
"dateTime": "2021-04-20T05:03:49.000000Z",
"created_at": null,
"updated_at": null
}
]

标签: apivue.jsaxiosvuetify.jsgoogle-maps-markers

解决方案


return this.Data.map,那是你的问题。return this.data.map

...
    axios(config).then((val) => {
      this.data = val.data; // Fix here
    });
  },

  computed: {
    google: gmapApi,

    markers() {
      return this.data.map( // Fix here
          (locationName,lat,long) => ({locationName, position: lat, long: long,})
      );
    },

推荐阅读