Evangeline
Evangeline

Reputation: 23

React/Leaflet - Error: Map container is already initialized

I'm trying to create a live map component using Leaflet in React (note: I'm not using React-Leaflet).

I'm fairly new to React so I'm sorry in advance for my messy code and/or if I'm being dumb. Every time I compile the app, the map works for a split second before giving me "Error: Map container is already initialized." The error stays and repeats itself while the app is running.

Here's my code (I've taken out my MapBox access token for this thread):

import React from 'react';
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';

let mymap;

export class Map extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      x: 0,
      y: 0,
      id: null
    }
  }


  componentDidMount() {
    this.getLocation();
  }

  componentWillUnmount() {
      navigator.geolocation.clearWatch(this.id);
      mymap.remove();
  }


  getLocation() {
    if (navigator.geolocation) {
      const success = (position) => {
        const xlocation = position.coords.latitude;
        const ylocation = position.coords.longitude;
        console.log("x: " + xlocation + " y: " + ylocation);
        this.setState({
          x: xlocation
        });
        this.setState({
          y: ylocation
        });
        console.log(this.state.x);
        mymap = L.map('mapid').setView([this.state.x, this.state.y], 13);

        L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}', {
        attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
        maxZoom: 18,
        id: 'mapbox/streets-v11',
        accessToken: 'redacted'
    }).addTo(mymap);
      };

      const options = {enableHighAccuracy: true, maximumAge: 10000};

      this.id = navigator.geolocation.watchPosition(success, (err) => {console.error('ERROR(' + err.code + '): ' + err.message)}, options);
    }
  }



  render(){

    return (
      <div id="mapid" className="responsive-map"></div>
    );
  }
}

If anyone could help me figure out what I'm misunderstanding that would be great! Thank you :)

Upvotes: 2

Views: 905

Answers (1)

Travnikov.dev
Travnikov.dev

Reputation: 464

You shouldn't use variables outside class. If you want store some variable throw the class you should define it in constructor like

constructor(props) {
  super(props);
  this.state = {
    x: 0,
    y: 0,
    id: null
  }
  this.map = null;
}

Also, you can't use calls like

this.id

because you define them throw the state, so you should call

this.state.id

And I definitely recommend you to start using react-leaflet - it's much easier to understand

Upvotes: 1

Related Questions