簡體   English   中英

未找到 React-Leaflet 標記文件

[英]React-Leaflet marker files not found

我有非常簡單的代碼來使用 react-leaflet 顯示地圖並在其上放置標記。 但是,我在瀏覽器控制台中收到以下兩個錯誤

GET http://localhost:8080/marker-icon-2x.png 404(未找到)

GET http://localhost:8080/marker-shadow.png 404(未找到)

我試圖通過下載這兩個圖像並將它們放在根目錄來解決這個問題。 有用。 但是,如何更改 react-leaflet 標記元素查找標記圖像的 URL? 我想將它們存儲在“./images”而不是根目錄中。

試着這樣做:)

由於某種原因,React傳單不包含圖像,您需要重置默認圖標圖像。

下面是一些工作示例,我希望它能解決您的問題。

您還可以從其中一個公共鏈接添加圖標

https://cdnjs.com/libraries/Leaflet.awesome-markers

import React, { Component } from 'react';
import L from 'leaflet';
import {
    Map, TileLayer, Marker, Popup
} from 'react-leaflet'
import 'leaflet/dist/leaflet.css';
import './style.css';


import icon from 'leaflet/dist/images/marker-icon.png';
import iconShadow from 'leaflet/dist/images/marker-shadow.png';

let DefaultIcon = L.icon({
    iconUrl: icon,
    shadowUrl: iconShadow
});

L.Marker.prototype.options.icon = DefaultIcon;

這是對我有用的解決方案:

我在文件頂部添加了以下幾行:

import { MapContainer, TileLayer, Marker, Popup } from 'react-leaflet';
import 'leaflet/dist/leaflet.css';
import L from 'leaflet';

delete L.Icon.Default.prototype._getIconUrl;

L.Icon.Default.mergeOptions({
    iconRetinaUrl: require('leaflet/dist/images/marker-icon-2x.png').default,
    iconUrl: require('leaflet/dist/images/marker-icon.png').default,
    shadowUrl: require('leaflet/dist/images/marker-shadow.png').default
});

當使用反應,傳單和反應傳單時,似乎並非所有東西都正確地整合在一起。 我有同樣的問題,發現了這一點

https://github.com/PaulLeCam/react-leaflet/issues/453

您需要再次設置leafelet本身,因為在導入leaflet.css之后會出現問題。

希望能幫助到你

將傳單包中的所有圖像復制到公共目錄:

cp node_modules/leaflet/dist/images/* {PUBLIC_WEB_DIRECTORY}/leaflet_images/

修復傳單中的路徑

import L from 'leaflet';
L.Icon.Default.imagePath='leaflet_images/';

為 Next.js 添加答案

  1. 將標記圖標從node_modules/leaflet/dist/images復制到public/images類似於/images/marker-icon.png

  2. 創建傳單圖標參考並在標記中使用參考

const icon = L.icon({ iconUrl: "/images/marker-icon.png" });

// some other code

<Marker key={obj.id} position={position} icon={icon}>

// rest of the code

最終為我解決這個問題的是刪除:

導入“傳單/dist/leaflet.css”;

來自我的地圖組件所在的文件。我最終通過 create-react-app index.html 文件導入了傳單 css,並且我的標記能夠與我的地圖一起加載。 希望這可以幫助任何卡住的人。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM