I would like to add the module "React-leaflet-locate-control" on Map. Unfortunately, I have this error "TypeError: Cannot read property 'addLayer' of undefined" and I don't know how to correct this error.
Can you help me please ?
Here is my component Map :
import './Map.css';
import React, { Component } from 'react';
import { Map, TileLayer, Marker, Popup } from 'react-leaflet';
import L from "leaflet";
import { getLat, getLng } from '../../Store.js';
import SearchBar from '../SearchBar/SearchBar.js';
import LocateControl from 'react-leaflet-locate-control';
const customMarker = new L.icon({
iconUrl: "https://unpkg.com/leaflet@1.4.0/dist/images/marker-icon.png",
iconSize: [25, 41],
iconAnchor: [13, 0]
});
export default class MapLeaflet extends Component {
constructor(props) {
super(props);
this.state = {
lat: getLat(),
lng: getLng(),
}
}
updateMarker = (e) => {
this.props.updateMarkerPosition(e.latlng.lat, e.latlng.lng);
this.setState({
lat: e.latlng.lat,
lng: e.latlng.lng
})
}
render() {
const position = [this.state.lat, this.state.lng]
const locateOptions = {
position: 'topright',
strings: {
title: 'Show me where I am, yo!'
},
onActivate: () => {} // callback before engine starts retrieving locations
}
return (
<div className="map">
<Map center={position} zoom={13} className="map" onClick={this.updateMarker}>
<TileLayer
attribution='&copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<Marker position={position} icon={customMarker}>
<Popup>
A pretty CSS3 popup. <br /> Easily customizable.
</Popup>
</Marker>
<SearchBar />
<LocateControl options={locateOptions} startDirectly/>
</Map>
</div>
)
}
}
react-leaflet-locate-control
package is not compatible with the latest version (v2) ofreact-leaflet
and in fact the similar issue has been reported hereSince
react-leaflet-locate-control
represents a wrapper forleaflet-locatecontrol
plugin, the following custom component forreact-leaflet
could be utilized instead which offers the same functionality asreact-leaflet-locate-control
:Here is a demo (source code)
If you are using Typescript like me. I made it work with
v2
using below component codeAdditionally, you can skip including Font awesome and library's own css files and provide your own styles instead
Geolocate.css
Of course you will have to install
leaflet.locatecontrol
usingnpm
firstnpm i leaflet.locatecontrol
Hope this helps.