我尝试了在网络上找到的所有东西,Stackoverflow和Github,我仍然无法做到。
我想用自定义图标制作自定义标记,但是我的代码总是出现错误:'TypeError:options.icon.createIcon不是函数'
这是我的代码(文件夹路径没有错误,一切都在src / js或src / img中)
Icon.js
import L from 'leaflet';
const iconPerson = L.Icon.extend({
options: {
iconUrl: require('../img/marker-pin-person.svg'),
iconRetinaUrl: require('../img/marker-pin-person.svg'),
iconAnchor: null,
popupAnchor: null,
shadowUrl: null,
shadowSize: null,
shadowAnchor: null,
iconSize: new L.Point(60, 75),
className: 'leaflet-div-icon'
}
});
export { iconPerson };
MarkerPinPerson
import React from 'react';
import { Marker } from 'react-leaflet';
import { iconPerson } from './Icons';
export default class MarkerPinPerson extends React.Component {
render() {
return (
<Marker
position={this.props.markerPosition}
icon={ iconPerson }
>
</Marker>
);
}
}
真的在寻求你的帮助!
答案 0 :(得分:13)
我终于找到了 Icon.js 文件的正确代码:
import L from 'leaflet';
const iconPerson = new L.Icon({
iconUrl: require('../img/marker-pin-person.svg'),
iconRetinaUrl: require('../img/marker-pin-person.svg'),
iconAnchor: null,
popupAnchor: null,
shadowUrl: null,
shadowSize: null,
shadowAnchor: null,
iconSize: new L.Point(60, 75),
className: 'leaflet-div-icon'
});
export { iconPerson };
答案 1 :(得分:0)
在试图弄清楚如何渲染自定义图标服务器端(使用react-leaflet-universal)时,我被带到这里。我以为我会发布此邮件,以防将来有人出于同样的原因而在这里找到自己。就像在react-leaflet-markercluster的情况下一样,我能够通过在return函数中要求传单来使此工作正常进行,例如:
<Map center={this.props.center}
zoom={zoom}
className={leafletMapContainerClassName}
scrollWheelZoom={false}
maxZoom={18}
preferCanvas={false}
>
{() => {
const MarkerClusterGroup = require('react-leaflet-markercluster').default;
const L = require('leaflet');
const myIcon = L.icon({
iconUrl: require('../assets/marker.svg'),
iconSize: [64,64],
iconAnchor: [32, 64],
popupAnchor: null,
shadowUrl: null,
shadowSize: null,
shadowAnchor: null
});
return (
<React.Fragment>
<TileLayer
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
attribution=''
setParams={true}
/>
<MarkerClusterGroup>
{coordArray.map(item => {
return (
<Marker icon={myIcon} key={item.toString()} position={[item.lat, item.lng]}>
{item.title && <Popup>
<span>{item.title}</span>
</Popup>}
</Marker>
)
})}
</MarkerClusterGroup>
</React.Fragment>
);
}}
</Map>
答案 2 :(得分:0)
您不需要使用require。无需提供iconUrl =“ ../assets/name”,只需导入png或svg,然后将源提供给iconUrl即可。看下面的例子:
//首先导入图片或svg
import heart from "../../images/other/love.svg";
//将来源提供给您的图标
let loveIcon = L.icon({
iconUrl: heart,
iconRetinaUrl: heart,
iconAnchor: [5, 55],
popupAnchor: [10, -44],
iconSize: [25, 55],
});
//只需将其添加到您的地图
L.marker([28, 50], {
icon: loveIcon,
}).addTo(map);
答案 3 :(得分:0)
我也遇到了同样的问题。 这是我的工作解决方案:
`import L from 'leaflet';
import marker from '../assets/placer.svg';
const myIcon = new L.Icon({
iconUrl: marker,
iconRetinaUrl: marker,
popupAnchor: [-0, -0],
iconSize: [32,45],
});`