简体   繁体   中英

marker leaflet doesnot render in react component _ React leaflet

this is my leaflet map component . I want to get reach cordinates when user clicks on map . I can get my cordinates correctly but I need to marker render on the map too.

<Map
        center={[35.4090, 51.1555]}
        zoom={18}
        maxZoom={20}
        attributionControl={true}
        zoomControl={true}
        onClick={this.handleClick}
        doubleClickZoom={false}
        scrollWheelZoom={true}
        dragging={true}
        animate={true}
        easeLinearity={0.35}
    >

        <Marker position={this.state.points === '' ? this.state.points : [35.4090, 51.1555]} icon={pointerIcon} key={this.state.points}>
            <Popup position={this.state.points}>
                Popup for any custom information.
                </Popup>
        </Marker>

    </Map>

 handleClick = (e) => {
        const { lat, lng } = e.latlng;
        this.setState({points: [lat,lng]})
    }

and this is custom Icon.

import marker from '../../css/mapMarker.png'
import L from 'leaflet'

export const pointerIcon = new L.Icon({
    iconUrl: {marker},
    iconRetinaUrl: {marker},
    iconAnchor: [5, 55],
    popupAnchor: [10, -44],
    iconSize: [25, 55],
    shadowSize: [68, 95],
    shadowAnchor: [20, 92],
})

In the provided example iconUrl and iconRetinaUrl properties are passed as an object values :

export const pointerIcon = new L.Icon({
    iconUrl: {marker},  
    iconRetinaUrl: {marker},
    //..
})

while for L.icon they are expected to be provided as a String values, that's most likely the reason why marker could not be displayed

So, either modify the example to initialize property as string data:

export const pointerIcon = new L.Icon({
    iconUrl: marker,  
    iconRetinaUrl: marker,
    //..
})

or specify Url as a property value, for example:

export const pointerIcon = new L.Icon({
    iconUrl: "https://maps.google.com/mapfiles/kml/pushpin/red-pushpin.png",  
    //..
}) 

Here is a demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM