问题描述
我无法在next.js中加载React传单标记。
我在这里称呼我的地图组件。
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="© <a href="http://osm.org/copyright">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文件。因此,从Google搜索开始,我添加了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的新手。
解决方法
我可以为您提供解决方案
我遇到了和你一样的问题,这对我有用:
我使用了这个库: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';
重新加载您的页面,您应该会看到应有的标记。