mbloch / mapshaper

Tools for editing Shapefile, GeoJSON, TopoJSON and CSV files
http://mapshaper.org
Other
3.67k stars 529 forks source link

How can I use mapshaper in vue3+vite project? #601

Closed Anqing-None closed 9 months ago

Anqing-None commented 9 months ago

I use npm installed the mapshaper package.

// package.json
"mapshaper": "^0.6.42",

Then, I import mapshaper in a vue component:

// x.vue
import { internal } from 'mapshaper'

Chrome browser will report an error:

main.ts:28 Error: Dynamic require of "iconv-lite" is not supported
    at chunk-AUZ3RYOM.js?v=3e773f76:12:9
    at mapshaper.js:3584:15
    at node_modules/mapshaper/mapshaper.js (mapshaper.js:44724:1)
    at __require2 (chunk-AUZ3RYOM.js?v=3e773f76:18:50)
    at mapshaper.js:44724:4

How can I fix it ?

mbloch commented 9 months ago

I might not be able to help with this... but can you tell me what part of mapshaper you want to use? Do you want to use any parts of the graphics user interface, or just some of the geoprocessing functions?

Anqing-None commented 9 months ago

I have a array like this:

// x means lng, y means lat
const mydata = [{ x: 0, y: 0, value: 0}, { x: 1, y: 1, value: 1}, ...]

I want to turn it into geojson format:

{
  "type":"FeatureCollection", 
  "features": [
    {
    "type":"Feature",
    "geometry":{"type":"Point", "coordinates":[0, 0]},
    "properties": {value: 0}
    },
    ...
   ]
}

I have read some source code, it use importJSONTable(content, opts);.

How can I pass opts to importJSONTable function to transfer mydata to geojson?

mbloch commented 9 months ago

importJSONTable() is an internal function that is not designed to be called directly. I would recommend using the API function applyCommands() (see https://github.com/mbloch/mapshaper/wiki/Using-mapshaper-programmatically#applycommands).

Your code would look something like this:

var cmd = "-i data.json -points x=x y=y -o format=geojson"
var output = await mapshaper.applyCommands(cmd, mydata);
var data = JSON.parse(output["data.json"]);

You can verify that the above command is correct using the mapshaper command line tool or the console in the web UI.

ThomasG77 commented 8 months ago

You can also create your own function for the purpose, not attached to mapshaper library in particular

const mydata = [{ x: 0, y: 0, value: 0}, { x: 1, y: 1, value: 1}]

const generateGeoJSONFromArray = data => {
  return {
    "type":"FeatureCollection", 
    "features": data.map(el => {
      const {x, y, ...properties} = el;
      return {
        "type":"Feature",
        "geometry":{
          "type":"Point",
          "coordinates":[x, y]
        },
        "properties": properties
      }
    })
  }
}

console.log(generateGeoJSONFromArray(mydata))