TypeError: Cannot read property 'getCanvasContainer' of undefined in React mapbox-gl project

2.2k views Asked by At

I'm building a React Mapbox project with mapboxgl (note: not the React wrapper version). So far I've been able to add what I'd like to the map and to my database, but I'm having trouble displaying all the data as markers/points/popups.

The message I get in Chrome is TypeError: Cannot read property 'getCanvasContainer' of undefined.

I'm wondering if this is a problem with my map itself (and lack of React wrapper for Mapbox) or with the coordinates. Right now I'm manually setting the coordinates as const coords, but if I don't, I get the message: Error: LngLatLike argument must be specified as a LngLat instance, an object {lng: , lat: }, an object {lon: , lat: }, or an array of [, ] which I've also been unable to solve. Here's some of my code to check out.

export default class Map extends Component {
    constructor(props) {
        super(props);
        this.state = {
        allBuildings: [],
        lng: 5,
        lat: 45,
        zoom: 3,
        }

        componentDidMount() {
            const map = new mapboxgl.Map({
            container: this.mapContainer,
            style: 'mapbox://styles/mapbox/streets-v11',
            center: [this.state.lng, this.state.lat],
            zoom: this.state.zoom
            });

            map.on('move', () => {
                this.setState({
                lng: map.getCenter().lng.toFixed(4),
                lat: map.getCenter().lat.toFixed(4),
                zoom: map.getZoom().toFixed(4)
                });
                });

            let marker = new mapboxgl.Marker({
                draggable: true,
                color: "blue"
            }).setLngLat([16.40, 50.54]).addTo(map) 


            marker.on('dragend', () => {
                const lngLat = marker.getLngLat();
                this.setState({
                    lng: lngLat.lng,
                    lat: lngLat.lat
                })
            })
            
            this.getMarkers()
            
            }

            getMarkers = () => {
                axios
                .get('/api/add')
                .then(res => {
                        this.setState({
                            allBuildings: res.data
                  res.data.forEach(building => {
                   const popup = new mapboxgl.Popup({ offset: 10})
                   const coords = [building.lng, building.lat]
                  new mapboxgl.Marker({
                       color: 'orange',
                       draggable: false })
                  .setPopup(popup)
                  .setLngLat(building.lng, building.lat)
                  .setHTML(<div>add later</div>)
                  .addTo(this.map)
                  })  
                })
                .catch(err => {
                    console.log(err)
                })
            }
0

There are 0 answers