React Leaflet - 将 pluscode 区域绘制为网格

React Leaflet - Draw pluscode areas as a grid

我正在尝试找出一种在 React Leaflet 上绘制 Pluscodes (OLC) 的方法。我可以通过扩展 GridLayer class 来绘制普通网格,但无法相应地绘制 pluscodes。我还没有完全弄清楚它是如何工作的。

我怎样才能做到这一点? GridLayer 适合这项任务还是我应该寻找其他东西?当我放大时,pluscodes 应该显示更高的级别。

https://codesandbox.io/s/pluscode-grid-problem-40fho?file=/src/App.jsx

// Grid.jsx
import { useEffect } from "react";
import L from "leaflet";
import { useLeafletContext } from "@react-leaflet/core";

const PlusCodeGrid = () => {
  const { layerContainer, map } = useLeafletContext();

  const createLeafletElement = () => {
    const Grid = L.GridLayer.extend({
      createTile: function (coords) {
        const tile = L.DomUtil.create("canvas", "leaflet-tile");

        tile.style.outline = "1px solid black";

        return tile;
      }
    });
    return new Grid({ tileSize: 100 });
  };

  useEffect(() => {
    layerContainer.addLayer(createLeafletElement());
  }, []);

  return null;
};

export default PlusCodeGrid;

// App.jsx
import React, { useState } from "react";
import { MapContainer, TileLayer, LayersControl } from "react-leaflet";
import PlusCodeGrid from "./Grid";
import { OpenLocationCode } from "open-location-code";

const getBoundariesFromPluscode = (plusCode) => {
  const geocoder = new OpenLocationCode();
  const { latitudeHi, latitudeLo, longitudeHi, longitudeLo } = geocoder.decode(
    plusCode
  );

  const boundary = [
    [latitudeLo, longitudeLo],
    [latitudeHi, longitudeHi]
  ];

  return boundary;
};

const App = () => {
  const [map, setMap] = useState(null);

  const plusCodeExample = "8FHJJMX2+R8";
  const plusCodeBoundaries = getBoundariesFromPluscode(plusCodeExample);

  console.log(plusCodeBoundaries);

  return (
    <div className="leaflet-container">
      <MapContainer
        className="map-container"
        whenCreated={setMap}
        zoom={15}
        scrollWheelZoom={true}
      >
        <LayersControl>
          <TileLayer url="http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" />
          <LayersControl.Overlay checked name="Pluscode Grid">
            <PlusCodeGrid />
          </LayersControl.Overlay>
        </LayersControl>
      </MapContainer>
    </div>
  );
};

export default App;

令人难以置信,答案就在我在问题中找到的页面中...我再次选择快速浏览文档以节省几分钟,结果却在这个过程中浪费了几天时间。

无论如何,grid.plus.codes 为 plus 代码提供了网格服务,可以像这样轻松地与 React 传单一起使用:

import { useEffect } from 'react';
import L from 'leaflet';
import { useLeafletContext } from '@react-leaflet/core';

const PlusCodeGrid = () => {
  const { layerContainer, map } = useLeafletContext();

  useEffect(() => {
    layerContainer.addLayer(
      L.tileLayer('https://{s}-grid.plus.codes/grid/tms/{z}/{x}/{y}.png', {
        tms: true,
        attribution: 'grid by plus codes',
      }).addTo(map)
    );
  }, []);

  return null;
};

export default PlusCodeGrid;