You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何调整地图坐标网格的gridOrder为左上到右下、从左到右排序?

问题分析

turf.js的pointGrid方法默认生成点的顺序是从南到北(纬度由低到高)、西到东(经度由低到高),也就是先填充最左侧列的下方点,再向上遍历,接着处理下一列。这导致你的gridOrder从左下角开始计数,不符合「左上到右、从上到下」的需求。

解决方案

我们需要先对生成的网格点进行排序:先按**纬度从高到低(从上到下)分组为行,同一行内按经度从低到高(从左到右)**排列,之后再分配gridOrder。

修改后的代码
import bbox from "@turf/bbox";
import { Units, point } from "@turf/helpers";
import pointGrid from "@turf/point-grid";
import buffer from "@turf/buffer";

const createGridCoordinates = (
  centerCoordinates: google.maps.LatLngLiteral,
  numPointsPerSide: number,
  gridDimension: number,
  unitOfMeasure: Units
) => {
  // Calculate the cell size
  const cellSize = gridDimension / (numPointsPerSide - 1);

  // Calculate half the grid size to find the distance from center to edges of bounding box
  const halfGridSize = gridDimension / 2;

  // Make the bounding box around a center point and a circle buffer radius
  // Radius is extended by 10% of a cellSize (cellSize / 10) to include
  // east and north edges when gridDimension is an exact multiple of the grid spacing
  const boundingBox = bbox(
    buffer(
      point([centerCoordinates.lng, centerCoordinates.lat]),
      halfGridSize + cellSize / 10,
      {
        units: unitOfMeasure,
      }
    )
  );

  // Make the grid. This is an array of grid coordinates.
  const grid = pointGrid(boundingBox, cellSize, {
    units: unitOfMeasure,
  });

  // 计算网格的最大纬度(最上方)和最小经度(最左侧)
  const allLats = grid.features.map(f => f.geometry.coordinates[1]);
  const maxLat = Math.max(...allLats);
  const allLngs = grid.features.map(f => f.geometry.coordinates[0]);
  const minLng = Math.min(...allLngs);

  // 对网格点排序:先按从上到下(纬度降序)分组为行,同一行按从左到右(经度升序)排列
  const sortedFeatures = grid.features.sort((a, b) => {
    const [aLng, aLat] = a.geometry.coordinates;
    const [bLng, bLat] = b.geometry.coordinates;

    // 计算行号:行号越小越靠上
    const rowA = Math.round((maxLat - aLat) / cellSize);
    const rowB = Math.round((maxLat - bLat) / cellSize);

    if (rowA !== rowB) {
      return rowA - rowB;
    }

    // 同一行计算列号:列号越小越靠左
    const colA = Math.round((aLng - minLng) / cellSize);
    const colB = Math.round((bLng - minLng) / cellSize);
    return colA - colB;
  });

  // 提取坐标并分配正确的gridOrder
  const coordinatesGrid = sortedFeatures.map((feature, index) => {
    const [longitude, latitude] = feature.geometry.coordinates;
    return {
      coordinates: { lat: latitude, lng: longitude },
      gridOrder: index + 1,
    };
  });

  return coordinatesGrid;
};
关键修改说明
  1. 计算网格的最大纬度(最顶部)和最小经度(最左侧),作为行号、列号的计算基准
  2. 通过cellSize计算每个点的行号和列号,避免浮点数精度误差导致的排序错误
  3. 先按行号升序(从上到下)排序,同一行内按列号升序(从左到右)排序
  4. 按排序后的顺序分配gridOrder,从1开始递增

修改后即可得到你期望的gridOrder显示:

1 | 2 | 3
---+---+---
 4 | 5 | 6
---+---+---
 7 | 8 | 9

内容的提问来源于stack exchange,提问作者TinyTiger

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 19:05:04