基于经纬度缩放绘制多边形:GD库实现无背景农田图形生成
使用GD库生成农田多边形无背景图像
需求说明
我有几块农田的经纬度坐标(可直接在地图上绘制),示例坐标如下:
45.60859921 19.24758575 45.60869489 19.24816738 45.60538637 19.24872261 45.60535008 19.24841258 45.60662288 19.24802522 45.60660895 19.24791747
我需要用GD库生成农田的无背景图像(仅显示农田轮廓填充的图形),要求:
- 输入参数为正方形图像的像素尺寸,以及农田的经纬度坐标集合
- 把多边形适配到带内边距的正方形画布中
- 这些农田最大只有几公顷,不需要精确投影,只要能呈现多边形的相对形状就行
PHP实现代码
<?php // 生成农田多边形图像的函数 function createFarmImage(int $imgSize, array $coords, int $padding = 20) { // 提取所有纬度和经度 $lats = array_column($coords, 0); $lons = array_column($coords, 1); // 计算坐标边界 $minLat = min($lats); $maxLat = max($lats); $minLon = min($lons); $maxLon = max($lons); // 计算缩放比例:适配内边距后的画布尺寸 $latSpan = $maxLat - $minLat; $lonSpan = $maxLon - $minLon; $maxSpan = max($latSpan, $lonSpan); $scale = ($imgSize - 2 * $padding) / $maxSpan; // 创建带透明背景的正方形图像 $image = imagecreatetruecolor($imgSize, $imgSize); imagesavealpha($image, true); $transparent = imagecolorallocatealpha($image, 0, 0, 0, 127); imagefill($image, 0, 0, $transparent); // 转换经纬度为画布像素坐标 $pixelPoints = []; foreach ($coords as $coord) { // 经度对应X轴,纬度对应Y轴(翻转Y轴,因为图像Y轴向下) $x = $padding + ($coord[1] - $minLon) * $scale; $y = $padding + ($maxLat - $coord[0]) * $scale; $pixelPoints[] = round($x); $pixelPoints[] = round($y); } // 设置颜色并绘制多边形 $fillColor = imagecolorallocate($image, 90, 185, 75); // 农田填充绿 $borderColor = imagecolorallocate($image, 45, 115, 35); // 边框深绿 imagefilledpolygon($image, $pixelPoints, count($coords), $fillColor); imagepolygon($image, $pixelPoints, count($coords), $borderColor); return $image; } // 使用示例 $farmCoords = [ [45.60859921, 19.24758575], [45.60869489, 19.24816738], [45.60538637, 19.24872261], [45.60535008, 19.24841258], [45.60662288, 19.24802522], [45.60660895, 19.24791747], ]; // 生成500x500的图像 $img = createFarmImage(500, $farmCoords); header('Content-Type: image/png'); imagepng($img); imagedestroy($img); ?>
代码说明
- 边界计算:先获取经纬度的最大最小值,确定坐标范围,为缩放做准备
- 缩放适配:以最大的坐标跨度为基准计算缩放比例,保证多边形能完整放入带内边距的画布
- 坐标转换:把经纬度映射到画布像素,翻转Y轴是因为图像的Y轴原点在顶部,而纬度数值越大越靠北(对应图像上方)
- 透明背景:通过
imagesavealpha和全透明颜色填充实现无背景效果 - 绘制细节:填充绿色模拟农田,添加深绿色边框让轮廓更清晰
内容的提问来源于stack exchange,提问作者Ilija
相关产品推荐
相关产品推荐

