如何解析澳大利亚郊区GeoJSON动态键坐标并导入MySQL数据库
解决澳大利亚郊区GeoJSON动态键坐标提取与数据库导入问题
核心思路
利用固定的澳大利亚州/领地缩写集合,遍历每个GeoJSON Feature的属性字段,匹配动态生成的{州缩写}_loca_2键,提取坐标数据后转成JSON字符串存入MySQL。
步骤与代码实现
1. 定义州缩写集合
先列出所有目标州/领地的缩写,用于匹配动态键:
$stateCodes = ['nsw', 'qld', 'nt', 'wa', 'sa', 'vic', 'act', 'tas'];
2. 解析GeoJSON文件
建议先将10MB的GeoJSON文件下载到本地再处理,避免重复网络请求:
$geoJsonContent = file_get_contents('australian-suburbs.geojson'); $geoData = json_decode($geoJsonContent, true); if (json_last_error() !== JSON_ERROR_NONE) { die("GeoJSON解析失败:" . json_last_error_msg()); }
3. 提取郊区名称与坐标
遍历每个Feature,匹配动态键并提取坐标集合:
$suburbRecords = []; foreach ($geoData['features'] as $feature) { $props = $feature['properties']; // 统一郊区名称为大写,匹配需求中的格式 $suburbName = strtoupper(trim($props['suburb'] ?? '')); if (empty($suburbName)) continue; $coordinates = null; // 遍历州缩写,查找对应的_loca_2键 foreach ($stateCodes as $code) { $targetKey = "{$code}_loca_2"; if (isset($props[$targetKey]['coordinates'])) { $coordinates = $props[$targetKey]['coordinates']; break; } } if ($coordinates) { // 将坐标数组转为JSON字符串,便于数据库存储 $coordsJson = json_encode($coordinates, JSON_UNESCAPED_SLASHES); $suburbRecords[] = [ 'suburb' => $suburbName, 'coords' => $coordsJson ]; } else { // 可选:记录无坐标的郊区,便于后续排查 error_log("无匹配坐标的郊区:{$suburbName}"); } }
4. 导入MySQL数据库
推荐用TEXT类型存储坐标字符串(避免VARCHAR的长度限制),先创建数据表:
CREATE TABLE suburbs ( id INT AUTO_INCREMENT PRIMARY KEY, suburb_name VARCHAR(255) NOT NULL UNIQUE, coordinates TEXT NOT NULL, INDEX idx_suburb_name (suburb_name) );
然后用PDO批量插入数据:
// 数据库连接配置 $dbConfig = [ 'host' => 'localhost', 'dbname' => 'your_database', 'user' => 'your_username', 'pass' => 'your_password' ]; try { $pdo = new PDO( "mysql:host={$dbConfig['host']};dbname={$dbConfig['dbname']};charset=utf8mb4", $dbConfig['user'], $dbConfig['pass'], [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION] ); // 准备插入语句 $stmt = $pdo->prepare("INSERT INTO suburbs (suburb_name, coordinates) VALUES (:suburb, :coords)"); // 批量插入数据 foreach ($suburbRecords as $record) { $stmt->execute([ ':suburb' => $record['suburb'], ':coords' => $record['coords'] ]); } echo "成功导入 " . count($suburbRecords) . " 条郊区数据"; } catch (PDOException $e) { die("数据库操作失败:" . $e->getMessage()); }
注意事项
- 内存优化:若10MB文件导致内存溢出,可使用
JSONStreamingParser等流式解析库,逐行处理GeoJSON数据。 - 数据去重:通过
UNIQUE约束确保郊区名称唯一,避免重复插入。 - 格式验证:提取坐标后可额外检查是否为合法的Polygon/MultiPolygon结构,过滤无效数据。
内容的提问来源于stack exchange,提问作者Australopythecus
相关产品推荐
相关产品推荐

