Как исправить ошибку типа при рисовании линии с помощью Mapbox - PullRequest
0 голосов
/ 15 мая 2019

Я работаю над проектом, в котором я использую API Mapbox для отображения велосипедных маршрутов.

Я последовал собственному примеру Mapbox по API, который можно найти здесь:

https://docs.mapbox.com/mapbox-gl-js/example/geojson-line/

Почему-то у меня ошибка, которая, кажется, вызвана неправильным типом, но я действительно не понимаю ее, не говоря уже о ее устранении.

Этот код работает, как в примере.

this.map.addLayer({
      id: 'geojson',
      type: 'line',
      source: {
        type: 'geojson',
        data: {
          type: 'Feature',
          properties: {},
          geometry: {
            type: 'LineString',
            coordinates: [
              [-122.48369693756104, 37.83381888486939],
              [-122.48348236083984, 37.83317489144141],
              [-122.48339653015138, 37.83270036637107],
              [-122.48356819152832, 37.832056363179625],
              [-122.48404026031496, 37.83114119107971],
              [-122.48404026031496, 37.83049717427869],
            ]
          }
        }
      },
      layout: {
        'line-join': 'round',
        'line-cap': 'round'
      },
      paint: {
        'line-color': '#888',
        'line-width': 8
      }

Но когда я удаляю жестко запрограммированные геопоинты и изменяю их на массив значений LatLong, основываясь на более раннем API-вызове, который я сделал в Mapbox для получения велосипедного маршрута, я получаю сообщение об ошибке:

this.map.addLayer({
      id: 'geojson',
      type: 'line',
      source: {
        type: 'geojson',
        data: {
          type: 'Feature',
          properties: {},
          geometry: {
            type: 'LineString',
            coordinates: this.directionsResult.routes[0].geometry.coordinates
          }
        }
      },
      layout: {
        'line-join': 'round',
        'line-cap': 'round'
      },
      paint: {
        'line-color': '#888',
        'line-width': 8
      }
    });

Сообщение об ошибке:

(property) mapboxgl.Layer.source?: string | mapboxgl.GeoJSONSourceRaw | mapboxgl.VideoSourceRaw | mapboxgl.ImageSourceRaw | mapboxgl.CanvasSourceRaw | mapboxgl.VectorSource | mapboxgl.RasterSource | mapboxgl.RasterDemSource
Type '{ type: string; data: { type: string; properties: {}; geometry: { type: string; coordinates: LatLong[]; }; }; }' is not assignable to type 'string | GeoJSONSourceRaw | VideoSourceRaw | ImageSourceRaw | CanvasSourceRaw | VectorSource | RasterSource | RasterDemSource'.
  Type '{ type: string; data: { type: string; properties: {}; geometry: { type: string; coordinates: LatLong[]; }; }; }' is not assignable to type 'GeoJSONSourceRaw'.
    Types of property 'type' are incompatible.
      Type 'string' is not assignable to type '"geojson"'.ts(2322)
index.d.ts(1298, 9): The expected type comes from property 'source' which is declared here on type 'Layer'.

Когда я сравниваю обозначения жестко закодированных геопоинт с моим результатом, я возвращаюсь из API направлений, они, кажется, имеют точно такой же тип и обозначение:

let coords = this.directionsResult.routes[0].geometry.coordinates;
let geometry = [
      [-122.48369693756104, 37.83381888486939],
      [-122.48348236083984, 37.83317489144141],
      [-122.48339653015138, 37.83270036637107],
      [-122.48356819152832, 37.832056363179625],
      [-122.48404026031496, 37.83114119107971],
      [-122.48404026031496, 37.83049717427869]
    ];

console.log(coords);
console.log(geometry);

Что дает мне следующий вывод на консоль:

(17) [Array(2), Array(2), Array(2), Array(2), Array(2), Array(2), Array(2), Array(2), Array(2), Array(2), Array(2), Array(2), Array(2), Array(2), Array(2), Array(2), Array(2)]
map-box.component.ts:94 

(6) [Array(2), Array(2), Array(2), Array(2), Array(2), Array(2)]

Кто-нибудь с некоторыми предложениями помощи о том, что я делаю здесь не так? Спасибо!

Ответы [ 2 ]

0 голосов
/ 18 мая 2019

Я не знаю почему, но когда я добавляю путевые точки к пустому объекту массива и использую его, он работает:

let coordsArray = new Array(0);

for (let item of this.directionsResult.routes[0].geometry.coordinates) {
  coordsArray.push(item);
}

А потом при добавлении маршрута Layer на карту:

this.map.addLayer({
      id: 'geojson',
      type: 'line',
      source: {
        type: 'geojson',
        data: {
          type: 'Feature',
          properties: {},
          geometry: {
            type: 'LineString',
            coordinates: coordsArray
          }
        }
      },
      layout: {
        'line-join': 'round',
        'line-cap': 'round'
      },
      paint: {
        'line-color': '#198e46',
        'line-width': 3
      }
    });
0 голосов
/ 15 мая 2019

Я считаю, что это потому, что вы вызываете строку вместо массива, попробуйте использовать [] следующим образом.

source: {type: 'geojson', data: {type: 'Feature', properties: {}, геометрия: [{type: 'LineString', координаты: this.directionsResult.routes [0] .geometry.coordinates}]}},

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...