下载安装
npm install --save shp-write
引用
import shpwrite from "shp-write";
修改源码
如果直接使用会发现,导出点图形是完全正常的,如果导出面图形的话,导出一个面图形的话是完全没有问题的。但是一个shp文件中包含多个面图形,在使用arcgis打开时就会报错。这是因为源代码把多个图形的coordinates给合并成为了一个[[[[1, 1], [1, 2], [2, 2], [2, 1], [1, 1]],[[1, 1], [1, 5], [5, 5], [5, 1], [1, 1]]]]这种形式。这样导出时是一个type为MultiPolygon的图形(多部件)。
此时需要我们自己去更改源代码。打开geojson文件
function justType(type, TYPE) {
return function(gj) {
var oftype = gj.features.filter(isType(type));
return {
// geometries: (TYPE === 'POLYGON' || TYPE === 'POLYLINE') ? oftype.map(justCoords): oftype.map(justCoords),
geometries:oftype.map(justCoords),
properties: oftype.map(justProps),
type: TYPE
};
};
}
function justCoords(t) {
// if (t.geometry.coordinates[0] !== undefined &&
// t.geometry.coordinates[0][0] !== undefined &&
// t.geometry.coordinates[0][0][0] !== undefined) {
// return t.geometry.coordinates;
// } else {
// return t.geometry.coordinates;
// }
return t.geometry.coordinates;
}
使用
const options = {
folder: "my-shp", //文件夹名称
types: {
point: "myPoint", //type为point的shp文件名称
polygon: "myPolyline",//type为polyline的shp文件名称
line: "mylines",//type为line的shp文件名称
},
}
const geoJsonPoint = {
type: "FeatureCollection",
features:
[
{
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [117.2152, 36.1254]
},//图形坐标
properties: {
name: '测试点1',
}//属性
},
{
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [117.2254, 36.1312]
},//图形坐标
properties: {
name: '测试点2',
}//属性
},
]
}
const geoJsonPolyline = {
type: "FeatureCollection",
features:
[
{
type: 'Feature',
geometry: {
type: 'LineString',//注意,这里不能写Line或Polyline,只能是LineString
coordinates: [[[117.2152, 36.1254], [117.2254, 36.1312]]]
},//图形坐标
properties: {
name: '测试线路1',
}//属性
},
{
type: 'Feature',
geometry: {
type: 'LineString',
coordinates: [[[117.2254, 36.3112], [117.2452, 36.3312]]]
},//图形坐标
properties: {
name: '测试线路2',
}//属性
},
]
}
const geoJsonPolygon = {
type: "FeatureCollection",
features:
[
{
type: 'Feature',
geometry: {
type: 'Polygon',
coordinates: [[[1, 1], [1, 2], [2, 2], [2, 1], [1, 1]]]
},//图形坐标
properties: {
name: '测试图形1',
}//属性
},
{
type: 'Feature',
geometry: {
type: 'Polygon',
coordinates: [[[1, 1], [1, 5], [5, 5], [5, 1], [1, 1]]]
},//图形坐标
properties: {
name: '测试图形2',
}//属性
},
]
}
shpwrite.download(geoJsonPoint, options);//下载point的shp文件
shpwrite.download(geoJsonPolyline, options);//下载polyline的shp文件
shpwrite.download(geoJsonPolygon, options);//下载polygon的shp文件
这里默认使用的是WGS84坐标系。如需导出别的坐标系更改prj.js文件中的内容即可