跳到内容
+

创建地图组件

您可以使用自定义代码组件扩展 Toolpad Studio。

您可以创建一个自定义组件来显示任何地理地图,如下所示

Map component

地图组件

创建组件

在 Toolpad Studio 编辑器中

  1. 要开始创建此组件,请悬停在组件库上,然后单击自定义组件部分中的 创建 按钮。
Create custom component

创建自定义组件

  1. 将出现一个对话框,要求您命名它。将其命名为“Map”。

Name custom component

命名自定义组件

  1. 将出现一个 snackbar,确认组件已成功创建。启动器文件在 toolpad/components 中创建。使用 打开 按钮在您的代码编辑器中打开此文件
Open custom component

打开自定义组件

在代码编辑器中

  1. 将为您初始化一个包含自定义组件示例代码的文件。将其内容替换为以下代码
import * as React from 'react';
import { createComponent } from '@toolpad/studio/browser';
import * as L from 'leaflet';

export interface LeafletProps {
  lat: number;
  long: number;
  zoom: number;
}

async function createLeafletStyles(doc) {
  let styles = doc.getElementById('leaflet-css');
  if (styles) {
    return;
  }
  const res = await fetch('https://esm.sh/leaflet/dist/leaflet.css');
  if (!res.ok) {
    throw new Error(`HTTP ${res.status}: ${res.statusText}`);
  }
  const css = await res.text();
  styles = doc.createElement('style');
  styles.id = 'leaflet-css';
  styles.appendChild(doc.createTextNode(css));
  doc.head.appendChild(styles);
}

function Leaflet({ lat, long, zoom }: LeafletProps) {
  const root: any = React.useRef(null);
  const mapRef = React.useRef<any>();
  const [stylesInitialized, setStylesIitialized] = React.useState(false);
  const [error, setError] = React.useState<Error>();

  React.useEffect(() => {
    const doc = root.current.ownerDocument;
    createLeafletStyles(doc).then(
      () => setStylesIitialized(true),
      (err) => setError(err),
    );
  }, []);

  React.useEffect(() => {
    if (!mapRef.current && stylesInitialized) {
      mapRef.current = L.map(root.current);
      L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        maxZoom: 19,
        attribution: '© OpenStreetMap',
      }).addTo(mapRef.current);
    }

    if (mapRef.current) {
      mapRef.current.setView([lat, long], zoom);
    }
  }, [stylesInitialized, lat, long, zoom]);

  return (
    <div style={{ height: 400, width: 600 }}>
      {error ? (
        error.message
      ) : (
        <div style={{ width: '100%', height: '100%' }} ref={root} />
      )}
    </div>
  );
}

export default createComponent(Leaflet, {
  argTypes: {
    lat: {
      type: 'number',
      defaultValue: 51.505,
    },
    long: {
      type: 'number',
      defaultValue: -0.09,
    },
    zoom: {
      type: 'number',
      defaultValue: 13,
    },
  },
});

labelvalue 是您将在 Toolpad Studio 编辑器中用于绑定的 props。

  1. MapDisplay 现在作为自定义组件在组件库中可用
map component in library

地图组件出现在组件库中

使用组件

  1. 将两个地图组件拖到画布上,然后选择第一个。在检查器中,您将看到 labelvalue 属性都作为可绑定属性提供。
Use map components with numbers and labels

使用地图组件