Leaflet Routing Machine Контейнер маршрута не отображается в шаблоне Vue - PullRequest
0 голосов
/ 25 января 2019

Так что у меня возникает странная проблема, когда я пытаюсь объединить машину маршрутизации листовок с компонентом в Vue.

После запуска .getPlan () на моем L.Routing.Control я пытаюсь использовать .onAdd (), чтобы получить контейнер маршрута. Я добавляю его к данным компонента, которые затем печатаются с использованием v-html в моем шаблоне.


Сценарий:

data () {
  return {
    currentStep: 'search',
    mode: this.initialMode,
    currentLocation: {},
    geocoder: new L.Control.Geocoder.Nominatim(),
    routingControl: new L.Routing.Control({ // <-- The routing control
      showAlternatives: false,
      createMarker: (i, wp, nWps) => {
        return L.marker(wp.latLng, {
          icon: L.icon({
            iconUrl: 'img/icons/DotIcon.png',
            iconSize: [33, 50],
            iconAnchor: [16, 50],
            popupAnchor: [0, -40]
          })
        })
      },
      lineOptions: {
        addWaypoints: false
      },
      router: L.Routing.mapbox(this.accessToken, {
        profile: 'mapbox/driving'
      }),
      formatter: new L.Routing.Formatter({
        units: 'imperial'
      })
    }),
    formatter: new L.Routing.Formatter(),
    itinerary: null,
    to: {},
    from: {}
  }
},

...

methods: {
  getDirections () {
    if (typeof this.from === 'undefined' ||
      typeof this.to === 'undefined') {
      return false
    }

    let waypoints = [
      [this.from.coordinates.lat, this.from.coordinates.lng],
      [this.to.coordinates.lat, this.to.coordinates.lng]
    ]

    this.$root.$emit('set-routing-control', this.routingControl)

    this.routingControl.setWaypoints(waypoints)

    let results = this.routingControl.getPlan()
    let map = results._map

    this.itinerary = this.routingControl.onAdd(map) // <-- Where I attempt to get the container

    this.currentStep = 'results'
  }
}

Шаблон:

<div v-else-if="currentStep === 'results'">
  <span v-html="itinerary"></span>
</div>

Выход:

<div data-v-38a90df8="" data-v-8dc7cce2="">
  <span data-v-38a90df8="">{
  "_leaflet_events": {}
  }</span>
</div>

Я получаю маршрутный контейнер, используя маршрут, задокументированный в этом посте .

Когда я запускаю console.log(this.itinerary), я получаю это в консоли: Console output

Размытое содержимое - это правильная информация о местоположении.

Надеюсь, этого достаточно, чтобы понять, что может пойти не так. Не стесняйтесь, дайте мне знать, если вам нужна дополнительная информация.


Редактировать

Мне удалось грубо взломать контейнер в слот, используя jQuery и ref, но это небрежно, и я все же предпочел бы использовать v-html, если это возможно. Вот код для всех, кто интересуется временным исправлением.

Сценарий:

methods: {
  async getDirections () {
    if (typeof this.from === 'undefined' ||
      typeof this.to === 'undefined') {
      return false
    }

    let waypoints = [
      [this.from.coordinates.lat, this.from.coordinates.lng],
      [this.to.coordinates.lat, this.to.coordinates.lng]
    ]

    this.$root.$emit('set-routing-control', this.routingControl)

    this.routingControl.setWaypoints(waypoints)

    // I modified the way I get the map here a bit, but it's the same map
    this.itinerary = this.routingControl.onAdd(this.routingControl._map) // <-- Get the itinerary in the same way as before

    this.currentStep = 'results'

    await this.$nextTick() // <-- Wait until the div is loaded into the DOM

    $(this.$refs.results).append(this.itinerary) // <-- Get the div and append the Itinerary container
  }
}

Шаблон:

<div ref="results" v-else-if="currentStep === 'results'" />
...