【问题标题】:Why is my custom React-leaflet marker not displaying on my map?为什么我的自定义 React 传单标记没有显示在我的地图上?
【发布时间】:2021-12-26 06:55:23
【问题描述】:

我正在尝试为我的传单组件制作一个自定义标记图标以做出反应。我正在定义一个图标类并尝试使 iconURL 成为我使用的 PNG 的位置。我遇到的问题是 iconURL 仅适用于'https://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|abcdef&chf=a,s,ee00FFFF'。

我还尝试在我的项目中使用 PNG 的目录,以及 google 提供的图标的 URL,例如 'https://fonts.google.com/icons?selected=Material%20Icons%20Outlined %3Acable%3A'。然而,这两者都不能正确显示图像。我使用的特定 PNG 有问题吗?我尝试用 L.Icon.Default.prototype.options.iconUrl 覆盖默认的 URL 图标,但它只是产生了相同的结果。下面还将显示尝试使用当前无法使用的图标时图标的外观。

(编辑:包括我的目录的图像以防万一)

 function OutageIndicator({ outage }) {
   const LeafIcon = L.Icon.extend({
      options: {
          iconSize:     [38, 95],
          shadowSize:   [50, 64],
          iconAnchor:   [22, 94],
          shadowAnchor: [4, 62],
          popupAnchor:  [-3, -76]
      }
    });

    L.Icon.Default.prototype.options.iconUrl = 'icons/marker.png';

    const streamingIcon = new LeafIcon({
      iconUrl:"icons/marker.png"
    });
    
  return !coords ? (
      "Loading"
    ) : (
      <Marker position={[coords.lat, coords.lng]} icon={streamingIcon}>
        <Popup className={outage.service_type}>
          {outage.service_type}: {outage.service_name}
        </Popup>
      </Marker>
    );
}

function OutageMap() {
//a bunch of other lines of code

  return (
    <>
      <button onClick={setReportIsOpenTrue}>Report Outage</button>
      <MapContainer center={[44, -85]} zoom={7} scrollWheelZoom={true}>
        <TileLayer
          attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        />

        {allOutages.map((mock) => (
          <OutageIndicator outage={mock} />
        ))}
      </MapContainer>
    </>
  );
}

export default OutageMap;

【问题讨论】:

  • 当浏览器尝试加载这些 URL 时,您的 DevTools 控制台和网络选项卡会显示什么?
  • marker.png:1 GET localhost:3000/icons/marker.png 404(未找到)我没有使用正确的图片目录地址吗? (我将图像更改为 marker.png 将在帖子中正确反映)
  • 如果有帮助,我还会附上我的目录图片

标签: javascript node.js reactjs leaflet react-leaflet


【解决方案1】:

由于您使用的是 React,因此可能在后台配置了一个 webpack 构建工具,带有一个文件或 url-loader。

在这种情况下,您必须导入或要求您的图标文件,以便 webpack 知道它必须将其包含在您的包中:

    const streamingIcon = new LeafIcon({
      iconUrl: require("./icons/marker.png")
    });

【讨论】:

    猜你喜欢
    • 2021-03-31
    • 2022-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-04
    • 2016-08-31
    • 2020-02-19
    相关资源
    最近更新 更多