2

How a custom react component which outputs Marker on map should be written? I need to have smth like this working:

import MyMarker from './MyMarker.js';

const builtMarker = (function() {
  const position = [51.520, -0.11];
  return (
    <MyMarker position={position}/>
  );
})();

render(
  <div>
    <h1>Hello, world!</h1>
    <div className="map">
        <Map center={center} zoom={13}>
            <TileLayer
            url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
            attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
            />
            {builtMarker}
        </Map>
    </div>
  </div>
  ,
  document.getElementById('example')
);

I made MyMarker component like that https://github.com/varya/react-leaftlet-test/blob/master/src/MyMarker.js but this gets error:

Uncaught TypeError: Cannot read property 'addLayer' of undefined

I guess the component should not only extend MapLayer but also provide special interface. What is missing? I could not find similar example in the docs.

Also, what should I do to output several Markers? I mean, in React it's required to be in a single wrapper. But it cannot be just <div> for the map. How this wrapper should be written?

PS: This is the repo where I demonstrate my case https://github.com/varya/react-leaftlet-test

2 Answers 2

1

I've had the same exact problem and, reading the documentation I found out that I needed to add a ref='map' to the map component and then pass it down with a prop map={this.props.map} to the children components, linking them to the actual leaflet Map as you would using leafletjs.

What happens inside is that it tries to to a map.addLayer(this) or something like that, finding map as undefined

0

For the current version of react-leaflet, "React-Leaflet uses React's context API to make Leaflet elements available to other element that need it.". So the error Uncaught TypeError: Cannot read property 'addLayer' of undefined indicates that the layerContainer could not be found (defaults to the leaflet map).

You can fix the error by sending the context accessed instance to the react-leaflet component

<MyMarker position={position} layerContainer={layerContainer} />

Not the answer you're looking for? Browse other questions tagged or ask your own question.