如何将HAM梅登黑德网格转经纬度并生成Leaflet可用JSON
生成适用于Leaflet的HAM方块坐标转换JSON数据
我来帮你搞定这个需求!Leaflet对GeoJSON格式支持最好,所以我们需要把数据库里的HAM方块坐标转换成经纬度,再打包成标准的GeoJSON结构输出。另外注意下,你原来用的mysql_*函数早就被PHP废弃了,我换成更安全的mysqli扩展来实现,避免后续的兼容性和安全问题。
完整实现代码
<?php // 数据库连接信息,根据你的实际情况修改 $host = 'localhost'; $dbname = 'your_database'; $username = 'your_username'; $password = 'your_password'; // 建立mysqli连接 $conn = new mysqli($host, $username, $password, $dbname); if ($conn->connect_error) { die("数据库连接失败: " . $conn->connect_error); } // 查询数据 $query = "SELECT * FROM maps"; $result = $conn->query($query); // 构建GeoJSON的FeatureCollection结构 $geojson = [ 'type' => 'FeatureCollection', 'features' => [] ]; while ($data = $result->fetch_assoc()) { // 提取HAM方块坐标 $loc = $data['user_loc']; // 转换为纬度(lat)和经度(lng) $lat = (ord(substr($loc, 1, 1)) - 65) * 10 - 90 + (ord(substr($loc, 3, 1)) - 48) + (ord(substr($loc, 5, 1)) - 65) / 24 + 1/48; $lng = (ord(substr($loc, 0, 1)) - 65) * 20 - 180 + (ord(substr($loc, 2, 1)) - 48) * 2 + (ord(substr($loc, 4, 1)) - 65) / 12 + 1/24; // 构建单个Feature(点要素) $feature = [ 'type' => 'Feature', 'geometry' => [ 'type' => 'Point', 'coordinates' => [$lng, $lat] // GeoJSON要求坐标顺序是[经度, 纬度] ], 'properties' => $data // 保留数据库里的其他字段作为属性 ]; // 添加到features数组 $geojson['features'][] = $feature; } // 输出JSON,设置正确的Content-Type头 header('Content-Type: application/json'); echo json_encode($geojson); // 关闭连接 $conn->close(); ?>
关键说明
- GeoJSON格式:Leaflet原生支持GeoJSON,所以我们用
FeatureCollection包裹所有点要素,每个点是一个Feature,包含geometry(点坐标)和properties(原始数据库字段),这样在Leaflet里可以直接用L.geoJSON()加载。 - 坐标顺序:GeoJSON的坐标是先经度,后纬度,和我们平时习惯的lat,lng顺序相反,这里要注意转换后的坐标顺序是
[$lng, $lat]。 - 废弃函数替换:把
mysql_*换成了mysqli扩展,这是PHP官方推荐的替代方案,安全性和兼容性更好。 - Content-Type头:输出时设置
application/json的响应头,确保前端能正确识别这是JSON数据。
在Leaflet中加载的示例
如果你需要在Leaflet里加载这个JSON,可以这样写:
// 假设你的PHP文件名为get_markers.php L.geoJSON('get_markers.php').addTo(map); // 也可以自定义点样式和弹窗 L.geoJSON('get_markers.php', { pointToLayer: function(feature, latlng) { return L.marker(latlng); }, onEachFeature: function(feature, layer) { // 弹窗显示属性信息,比如用户名 layer.bindPopup(feature.properties.username); } }).addTo(map);
内容的提问来源于stack exchange,提问作者tjakob
相关产品推荐
相关产品推荐

