Компонент карты иногда выдает ошибку: Uncaught (в обещании), "H.map.DataModel # add (Аргумент # 0 [объект Object])" - PullRequest
0 голосов
/ 21 января 2020

Я использую Here Maps (план Freemium) в приложении VueJs, которое использует vue -router .

Я сделал компонент Vue для отображения карты который использует Routing для создания SVG-пути между двумя точками, следующими за этими статьями:

Я включил библиотеку Here Maps ver 3.1 (CDN):

https://js.api.here.com/v3/3.1/mapsjs-service.js
https://js.api.here.com/v3/3.1/mapsjs-data.js
https://js.api.here.com/v3/3.1/mapsjs-ui.js
https://js.api.here.com/v3/3.1/mapsjs-mapevents.js

Но компонент Vue иногда выдает ошибку: Uncaught (in promise) D {message: "H.map.DataModel#add (Argument #0 [object Object])" Я заметил следующее:

  • Если я перезагружаю страницу, иногда она работает нормально, а иногда нет
  • С определенными путями маршрута она работает каждый раз

Я так старался найти проблема, не повезло. Я думаю, может быть, это сочетание vue -router и загрузки библиотеки Here Maps через CDN, которая вызывает эту проблему.

Существует ли пакет npm для Here Maps? Вы также сталкивались с этой проблемой?

Вот код моей карты Vue компонент.

<template>
  <div>
    <div ref="map" class="here-map__map" />
  </div>
</template>
<script>
export default {
  data() {
    return {
      map: {},
      coordinates: { lat: 46, lng: 12 },
      platform: {},
      waypoints: [],
      markers: [],
      icon: ''
    }
  },

  props: {
    property: {
      zoom: 8,
      markerIcon: "marker",
      routing: {
        route": {
          color: "#ff815b",
          width: 3
        },
        mode: {
          type: "fastest",
          transport: "truck",
          traffic: "traffic:disabled"
        }
      }
    },
    appId: YOUR_APP_ID,
    appCode: YOUR_APP_CODE
  },

  computed: {
    route() {
      return this.property.routing.route
    },

    routingParameters() {
      return {
        mode:
          this.property.routing && this.property.routing.mode
            ? Object.values(this.property.routing.mode).join(';')
            : ''
      }
    }
  },

  async created() {
    await this.initMap()
  },

  beforeDestroy() {
    this.map = null
  },

  methods: {
    async initMap() {
      this.platform = await new H.service.Platform({
        apikey: YOUR_API_KEY
      })
      await this.getCoordinates()
      this.createMap()
    },

    getCoordinates() {
      if (this.property.lat && this.property.lng) {
        this.coordinates = { lat: this.property.lat, lng: this.property.lng }
      } else {
        this.getGeoCoordinates()
      }
    },

    getGeoCoordinates() {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(pos => {
          this.coordinates = {
            lat: pos.coords.latitude,
            lng: pos.coords.longitude
          }
        })
      } else {
        console.warn('This browser does not support geolocalization.')
      }
    },

    calculateWaypoints() {
      if (this.property.routing && this.property.routing.waypoints) {
        this.waypoints = this.property.routing.waypoints.map((item, index) => {
          this.routingParameters[`waypoint${index}`] = `geo!${item.lat},${
            item.lng
          }`
        })
      } else {
        this.routingParameters.waypoint0 = this.shipment
          ? `geo!${this.shipment.from_address.lat},${
              this.shipment.from_address.lng
            }`
          : null
        this.routingParameters.waypoint1 = this.shipment
          ? `geo!${this.shipment.to_address.lat},${
              this.shipment.to_address.lng
            }`
          : null
      }
    },

    calculateRoute() {
      this.platform.getRoutingService().calculateRoute(
        this.routingParameters,
        result => {
          if (result.response.route) {
            let route = result.response.route[0]

            let lineString = new H.geo.LineString()
            route.shape.forEach(function(point) {
              let parts = point.split(',')
              lineString.pushLatLngAlt(parts[0], parts[1])
            })

            let routeLine = lineString
              ? new H.map.Polyline(lineString, {
                  style: {
                    strokeColor: this.route.color || '#000000',
                    lineWidth: this.route.width || 2
                  }
                })
              : null
            this.drawWaypoints(route)

            let mapObjects = [...this.markers, routeLine]
            this.map.addObjects(mapObjects)

            this.map.getViewModel().setLookAtData({
              bounds: routeLine.getBoundingBox()
            })
          }
        },
        error => {
          console.log(error)
        }
      )
    },

    drawWaypoints(route) {
      route.waypoint.map(({ mappedPosition }, index) => {
        this.markers.push(
          new H.map.Marker(
            {
              lat: mappedPosition.latitude,
              lng: mappedPosition.longitude
            },
            { icon: this.icon }
          )
        )
      })
    },

    async createMap() {
      this.icon = new H.map.Icon(`/${this.property.markerIcon}.svg`)
      let defaultLayers = await this.platform.createDefaultLayers()
      this.map = new H.Map(
        this.$refs[this.ref],
        defaultLayers.vector.normal.map,
        {
          zoom: this.property.zoom,
          center: this.coordinates
        }
      )

      let events = new H.mapevents.MapEvents(this.map)

      let behavior = new H.mapevents.Behavior(events)

      let ui = H.ui.UI.createDefault(this.map, defaultLayers)

      this.calculateWaypoints()
      this.calculateRoute()

      window.addEventListener('resize', () => {
        this.map.getViewPort().resize()
      })
    }
  }
}
</script>
<style lang="scss">
.here-map {
  &__map {
    height: 400px;
    margin: 0 auto;
  }
}
</style>

Заранее спасибо.

...