簡體   English   中英

JS 和 Svelte:將 JS 轉換為 GeoJSON 時出錯 - 解析失敗意外令牌 (1:7)

[英]JS and Svelte: Error converting JS to GeoJSON - Parse failure Unexpected token (1:7)

我有看起來像這樣的 CSV 文件。 我需要將其轉換為 GeoJSON 格式以使用 Mapbox 將其可視化。 我使用了 Mapbox 中 geojson 的外觀參考,並編寫了以下腳本,該腳本可以從我擁有的數據中生成類似的文件:

const fs = require('fs');
const CWD = process.cwd();
const { parse } = require('csv/sync');
const inPath = `${CWD}/src/data/`;
const outPath = `${CWD}/src/data/`;
// Read file
const csv = fs.readFileSync(`${inPath}organizations.csv`, 'utf8');

const json = parse(csv, { columns: true });
const jsonWithId = json.map((el, i) => ({ ...el, id: i + 1 }));
const features = jsonWithId.map(el => ({
    type: 'Feature',
    properties: el,
    geometry: {
        type: 'Point',
        coordinates: [el.scatterLong, el.scatterLat ]
    }
}));
// Create the feature collection
const featureCollection = {
    type: 'FeatureCollection',
    crs: {
        type: 'name',
        properties: {
            name: 'urn:ogc:def:crs:OGC:1.3:CRS84'
        },
}, 
features: features

};
// Write the GEOJSON file
fs.writeFileSync(`${outPath}organizations.geojson`, JSON.stringify(featureCollection));

這會轉換我的文件並生成這個 geojson ,這似乎是正確的結果。 當我嘗試像這里一樣在 JSFiddle 上運行它時,一切正常。 但是,當我將相同的代碼復制到我的 Svelte 網站並像這樣運行它時:

import { mapbox, key } from './mapbox.js';
import { setContext } from 'svelte';
import geoData from "$data/organizations.geojson"
    setContext(key, {
        getMap: () => map,
    });
    // Function load to create a new map and add to div
const load = () => {
    map = new mapbox.Map({
        container: container,
        style: 'mapbox://styles/username/cl4ktlt35001d16mim8rtqh8i',
        center: [-103.5917, 40.6699],
        zoom: 3
    });

    map.on('load', () => {
        map.addSource('earthquakes', {
            type: 'geojson',
            data: geoData,
            cluster: true,
            clusterMaxZoom: 14, // Max zoom to cluster points on
            clusterRadius: 50 // Radius of each cluster when clustering points (defaults to 50)
        });

// Rest of the code

我收到以下錯誤:

500
Parse failure: Unexpected token (1:7)
Contents of line 1: [the entire contents of the file follow]

這是什么意思? 我的文件有什么問題,為什么它在 JSFiddle 上運行良好,但在我的實際網站上卻沒有? 我該如何解決這個問題?

我假設您調用load的方式/時間有問題,因為它在REPL中使用類似這樣的操作和 JSFiddle 中的代碼並給出相同的結果(不確定公開 accessToken 是否明智?如果不要讓我知道,我會刪除 REPL)

使用mapbox-gl的官方教程context-api部分

mapboxgl.js
import mapboxgl from 'mapbox-gl';

// https://docs.mapbox.com/help/glossary/access-token/
mapboxgl.accessToken = '*****';

const key = Symbol();

export { mapboxgl, key };
Map.svelte
<script>
    import { onDestroy, setContext } from 'svelte';
    import { mapboxgl, key } from './mapboxgl.js';

    setContext(key, {
        getMap: () => map,
    });

    let map
    
    function initMap(container) {
        
        map = new mapboxgl.Map({
            container: container,
            style: 'mapbox://styles/mapbox/dark-v10',
            center: [-103.5917, 40.6699],
            zoom: 3
        });

        map.on('load', () => {
            // Add a new source from our GeoJSON data and
            // set the 'cluster' option to true. GL-JS will
            // add the point_count property to your source data.
            map.addSource('earthquakes', {
                type: 'geojson',
                // Point to GeoJSON data. This example visualizes all M1.0+ earthquakes
                // from 12/22/15 to 1/21/16 as logged by USGS' Earthquake hazards program.
                data: 'https://gist.githubusercontent.com/thedivtagguy/0a07453f2081be9c0f5b6fc2a2681a0f/raw/3c41dbbba93f88a78af1cf13e88443d2eed7d6ec/geodata.geojson',
                cluster: true,
                clusterMaxZoom: 14, // Max zoom to cluster points on
                clusterRadius: 50 // Radius of each cluster when clustering points (defaults to 50)
            });

            map.addLayer({
                id: 'clusters',
                type: 'circle',
                source: 'earthquakes',
                filter: ['has', 'point_count'],
                paint: {
                    // Use step expressions (https://docs.mapbox.com/mapbox-gl-js/style-spec/#expressions-step)
                    // with three steps to implement three types of circles:
                    //   * Blue, 20px circles when point count is less than 100
                    //   * Yellow, 30px circles when point count is between 100 and 750
                    //   * Pink, 40px circles when point count is greater than or equal to 750
                    'circle-color': [
                        'step',
                        ['get', 'point_count'],
                        '#51bbd6',
                        100,
                        '#f1f075',
                        750,
                        '#f28cb1'
                    ],
                    'circle-radius': [
                        'step',
                        ['get', 'point_count'],
                        20,
                        100,
                        30,
                        750,
                        40
                    ]
                }
            });

            map.addLayer({
                id: 'cluster-count',
                type: 'symbol',
                source: 'earthquakes',
                filter: ['has', 'point_count'],
                layout: {
                    'text-field': '{point_count_abbreviated}',
                    'text-font': ['DIN Offc Pro Medium', 'Arial Unicode MS Bold'],
                    'text-size': 12
                }
            });

            map.addLayer({
                id: 'unclustered-point',
                type: 'circle',
                source: 'earthquakes',
                filter: ['!', ['has', 'point_count']],
                paint: {
                    'circle-color': '#11b4da',
                    'circle-radius': 4,
                    'circle-stroke-width': 1,
                    'circle-stroke-color': '#fff'
                }
            });

            // inspect a cluster on click
            map.on('click', 'clusters', (e) => {
                const features = map.queryRenderedFeatures(e.point, {
                    layers: ['clusters']
                });
                const clusterId = features[0].properties.cluster_id;
                map.getSource('earthquakes').getClusterExpansionZoom(
                    clusterId,
                    (err, zoom) => {
                        if (err) return;

                        map.easeTo({
                            center: features[0].geometry.coordinates,
                            zoom: zoom
                        });
                    }
                );
            });

            // When a click event occurs on a feature in
            // the unclustered-point layer, open a popup at
            // the location of the feature, with
            // description HTML from its properties.
            map.on('click', 'unclustered-point', (e) => {
                const coordinates = e.features[0].geometry.coordinates.slice();
                const mag = e.features[0].properties.mag;
                const tsunami =
                            e.features[0].properties.tsunami === 1 ? 'yes' : 'no';

                // Ensure that if the map is zoomed out such that
                // multiple copies of the feature are visible, the
                // popup appears over the copy being pointed to.
                while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) {
                    coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;
                }

                new mapboxgl.Popup()
                    .setLngLat(coordinates)
                    .setHTML(
                    `magnitude: ${mag}<br>Was there a tsunami?: ${tsunami}`
                )
                    .addTo(map);
            });

            map.on('mouseenter', 'clusters', () => {
                map.getCanvas().style.cursor = 'pointer';
            });
            map.on('mouseleave', 'clusters', () => {
                map.getCanvas().style.cursor = '';
            });
        });

    }
</script>

<div use:initMap></div>

<style>
    div {
        position: absolute;
        inset: 0 0 80px 0;
    }
</style>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM