【问题标题】:unable to load marker in react leaflet next.js无法在反应传单 next.js 中加载标记
【发布时间】:2020-12-18 11:12:24
【问题描述】:

我无法在 next.js 中加载反应传单标记。

在这里我调用了我的地图组件。

const MapSearch = dynamic(import('../../components/Map'), {
  ssr: false,
  loading: () => (
    <div style={{textAlign: 'center', paddingTop: 20}}>
      Chargement…
    </div>
  )
})

const Map = () => (
    <MapSearch />
)

这是我的组件

 import React, { useState } from 'react';
import L from 'leaflet';

import { Map, Marker, Popup, TileLayer } from 'react-leaflet';

const LeafletMap = () => {
  const [coordinates, setCoordinates] = useState({
    lat: 51.505,
    lng: -0.09,
    zoom: 13,
  });
  React.useEffect(() => {
    const L = require("leaflet");

    delete L.Icon.Default.prototype._getIconUrl;

    L.Icon.Default.mergeOptions({
       iconUrl: require('leaflet/dist/images/marker-icon.png'),
       shadowUrl: require('leaflet/dist/images/marker-shadow.png')
    });
  }, []);
  const position = [coordinates.lat, coordinates.lng];
  return (
    <Map center={position} zoom={coordinates.zoom} style={{ width: '100%', height: '600px' }}>
      <TileLayer
        attribution="&copy; <a href=&quot;http://osm.org/copyright&quot;>OpenStreetMap</a> contributors"
        url="http://{s}.tile.osm.org/{z}/{x}/{y}.png"
      />
      <Marker position={position}>
        <Popup>
          <span>
            Marker 1 <br /> Easily customizable.
          </span>
        </Popup>
      </Marker>
    </Map>
  );
};


export default LeafletMap;

我收到错误,您需要添加加载程序来处理 png 文件。所以从谷歌搜索我添加了 next.config.js 并添加了以下代码

 module.exports = {
  webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
    config.module.rules.push({
      test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
      loader: require.resolve("url-loader")
    });

    return config;
  }
};

现在当我加载页面地图时正在加载但标记未加载。当我检查标记 img src 作为对象模块时。

我也尝试删除 L.Icon.Default.mergeOptions 行,但在这种情况下,我收到错误 http://localhost:3000/_next/static/media/marker-icon.1e8408af1a34bdf614570719b0d6e5ce.png%22)marker- icon.png 404(未找到)。

我是 Next.js 的新手。

【问题讨论】:

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


    【解决方案1】:

    我可能会为您提供解决方案

    我和你有同样的问题,我为我工作:

    我使用了这个库:https://github.com/ghybs/leaflet-defaulticon-compatibility

    首先运行以下命令:

    npm install leaflet-defaulticon-compatibility --save
    

    然后在您尝试实现地图的文件中(对我来说是 Map.js),只需添加以下导入:

    import { MapContainer, Marker, Popup, TileLayer } from 'react-leaflet';
    import 'leaflet/dist/leaflet.css';
    import 'leaflet-defaulticon-compatibility/dist/leaflet-defaulticon-compatibility.webpack.css'; // Re-uses images from ~leaflet package
    import 'leaflet-defaulticon-compatibility';
    

    重新加载您的页面,您应该会看到应有的标记。

    【讨论】:

      猜你喜欢
      • 2022-08-14
      • 2023-03-28
      • 1970-01-01
      • 2023-01-30
      • 2017-07-16
      • 2017-10-17
      • 1970-01-01
      • 2022-08-18
      • 1970-01-01
      相关资源
      最近更新 更多