如何将JavaScript生成的GeoJSON数据导入MySQL数据库?
将GeoJSON数据导入MySQL的分步解决方案
需求回顾
需要把JavaScript生成的GeoJSON数据导入MySQL,要求存储三列数据:
- 几何类型(Point/Polygon等)
- 属性(如颜色)
- 坐标(或对应的空间对象)
同时实现自动导入,解决不同几何类型坐标结构差异的问题。
第一步:创建目标数据表
先创建符合需求的表,用GEOMETRY类型存储空间对象(支持所有几何类型),JSON类型存储属性和坐标(适配不同结构的坐标数据):
CREATE TABLE spatial_data ( id INT AUTO_INCREMENT PRIMARY KEY, geometry_type VARCHAR(20) NOT NULL, properties JSON, geom GEOMETRY NOT NULL SRID 4326, -- SRID 4326对应WGS84经纬度坐标系 coordinates JSON -- 可选:单独存储坐标的JSON结构 );
第二步:拆分GeoJSON并导入数据
利用JSON_TABLE遍历GeoJSON中的features数组,结合空间函数提取所需字段,一次性插入数据:
INSERT INTO spatial_data (geometry_type, properties, geom, coordinates) SELECT JSON_UNQUOTE(JSON_EXTRACT(feature, '$.geometry.type')) AS geometry_type, JSON_EXTRACT(feature, '$.properties') AS properties, ST_GeomFromGeoJSON(JSON_EXTRACT(feature, '$.geometry')) AS geom, JSON_EXTRACT(feature, '$.geometry.coordinates') AS coordinates FROM JSON_TABLE( '{ "type": "FeatureCollection", "features": [ {"type": "Feature", "properties": {"color": "red"}, "geometry": {"type": "Point", "coordinates": [8.721926, 49.856657]}}, {"type": "Feature", "properties": {"color": "blue"}, "geometry": {"type": "Polygon", "coordinates": [[[8.428072, 50.052724],[8.428072, 50.190024],[8.807062, 50.190024],[8.807062, 50.052724],[8.428072, 50.052724]]]}}, {"type": "Feature", "properties": {"color": "green"}, "geometry": {"type": "Point", "coordinates": [9.177812, 50.151338]}} ] }', '$.features[*]' COLUMNS ( feature JSON PATH '$' ) ) AS jt;
第三步:验证导入结果
执行查询查看数据是否正确拆分:
SELECT id, geometry_type, JSON_PRETTY(properties) AS properties, ST_AsText(geom) AS wkt_geometry, JSON_PRETTY(coordinates) AS coordinates FROM spatial_data;
自动导入方案
如果GeoJSON是本地文件,可以结合JavaScript(和你生成数据的语言一致)实现自动读取并导入:
const mysql = require('mysql2/promise'); const fs = require('fs'); async function importGeoJSON() { // 建立数据库连接 const connection = await mysql.createConnection({ host: 'localhost', user: '你的数据库用户名', password: '你的数据库密码', database: '你的数据库名' }); // 读取本地GeoJSON文件 const geoJSONContent = fs.readFileSync('你的GeoJSON文件路径.geojson', 'utf8'); // 执行插入语句 const importQuery = ` INSERT INTO spatial_data (geometry_type, properties, geom, coordinates) SELECT JSON_UNQUOTE(JSON_EXTRACT(feature, '$.geometry.type')) AS geometry_type, JSON_EXTRACT(feature, '$.properties') AS properties, ST_GeomFromGeoJSON(JSON_EXTRACT(feature, '$.geometry')) AS geom, JSON_EXTRACT(feature, '$.geometry.coordinates') AS coordinates FROM JSON_TABLE(?, '$.features[*]' COLUMNS (feature JSON PATH '$')) AS jt; `; await connection.execute(importQuery, [geoJSONContent]); await connection.end(); console.log('GeoJSON数据导入完成'); } importGeoJSON();
你之前尝试的问题说明
- ST_GeomFromGeoJSON直接处理FeatureCollection:会生成
GEOMETRYCOLLECTION类型,把所有几何对象合并到同一列,无法拆分出单个几何的类型和属性。 - JSON_TABLE路径错误:你的查询用
$[*]遍历顶级元素,但FeatureCollection的顶级是对象,features才是需要遍历的数组;另外geometry是单个对象而非数组,不需要用nested path '$.geometry[*]',直接提取即可。
内容的提问来源于stack exchange,提问作者Melina M
相关产品推荐
相关产品推荐

