首页 > 解决方案 > 在 Vue 中初始化“marker-animate-unobtrusive”失败

问题描述

我正在尝试使用 marker-animate-unobtrusive 但我不断收到此错误:

在此处输入图像描述

我在SO上发现了另一篇文章,谈到在 google 加载后需要该文件,但我不知道该怎么做。在我的组件中,我有这个:

import SlidingMarker from 'marker-animate-unobtrusive'

在我的安装方法中,我有这个:

SlidingMarker.initializeGlobally()

任何帮助是极大的赞赏

标签: javascriptgoogle-mapsvue.js

解决方案


This is expected error since SlidingMarker extends google.maps.Marker class, GoogleMaps JavaScript API library needs to be loaded first, one option would to add a reference via index.html file:

<script src="https://maps.googleapis.com/maps/api/js?key=--KEY-GOES-HERE--"></script>   

Another option would to utilize async JavaScript loader, e.g. scriptjs. The example for loading GoogleMaps JavaScript API and marker-animate-unobtrusive module could look like this:

created: function(){
  get("https://maps.googleapis.com/maps/api/js?key=", () => {

    const SlidingMarker = require('marker-animate-unobtrusive')
    SlidingMarker.initializeGlobally()

    const map = new google.maps.Map(document.getElementById('map'), this.mapOptions);

    const marker = new SlidingMarker({
        position: this.mapOptions.center,
        map: map,
        title: 'Im sliding marker'
    });
 });

}

Here is a demo for your reference

Update

With vue-google-maps library marker-animate-unobtrusive plugin could be integrated like this:

<template>
  <div>
    <GmapMap :center="center" :zoom="zoom" ref="mapRef"></GmapMap>
  </div>
</template>

<script>

/* global google */

export default {
  data() {
    return {
      zoom: 12,
      center: { lat: 51.5287718, lng: -0.2416804 },
    };
  },
  mounted: function() {
     this.$refs.mapRef.$mapPromise.then(() => {
        this.initSlidingMarker(this.$refs.mapRef.$mapObject)
    })
  },
  methods: {
    initSlidingMarker(map){
       const SlidingMarker = require('marker-animate-unobtrusive')
       SlidingMarker.initializeGlobally()


       const marker = new SlidingMarker({
            position: map.getCenter(),
            map: map,
            title: 'Im sliding marker'
       });

       google.maps.event.addListener(map, 'click', (event) => {
          marker.setDuration(1000);
          marker.setEasing('linear');
          marker.setPosition(event.latLng);
       });
    }
  }
}
</script>

<style>
.vue-map-container {
  height: 640px;
}
</style>

推荐阅读