Popup won't stay open in react-leaflet after marker's onClick event

Viewed 599

I have a leaflet map that creates markers from the API data. Markers have onClick methods, that fetch data from the open weather API unsing marker's lat and lon. The weather data must be shown on the popup, but popup won't stay open, after onClick popup only flashes and won't stay open. I can see that the weather data is there. I think it might be the setState method that closes the popup. How can I keep the popup open? Thank you.

Here is the Map component

import React, { Component } from 'react';
import L, { tooltip } from 'leaflet';
import { Map, Marker, Popup, TileLayer } from 'react-leaflet';
import { Button } from 'react-bootstrap';

const position = [62.241581, 25.758742];
let weather = [];



class Kartta extends Component {
  constructor(props) {
    super(props);
    this.state = {
        places: [],
        sijaintisi: [],
        map: null,
        userLocation: [62.241581, 25.758742],
        weather: [],
        position: [62.241581, 25.758742],
        zoom: 7
    };

}
  componentDidMount() {
    this.getUserLocation();
  }

  componentDidUpdate() {
    console.log('update0');
    if (this.props.updateMap) {
      console.log('update1');
      if (this.props.updateMap !== this.state.places) {
        console.log('update2');
        this.setState({
          places: this.props.updateMap
        })
      }
    }
  }

  fetchPosition = (tänne) => {
    this.setState({ sijaintisi: tänne})
  }

  fetchWeather = (lat, lon) => {
    fetch('http://myurl/api/v1/wheather?lat=' + lat + '&lon=' + lon)
    .then(res => res.json())
    .then((data) => {
        this.setState({ weather: data })
    })
    .catch(console.log(this.state.weather))
  }

  iconSize = (iconName) => {
    var icon = iconName.toLowerCase().split('/')[0]
    if (icon === 'kuntokeskus' || icon === 'kuntosali' || icon === 'tekojääkenttä') {
      return 20, 30
    }
    else if (icon === 'ulkoilumaja' || icon === 'kampailulajien sali' || icon === 'koripallokenttä') {
      return 30, 30
    }
    else if (icon === 'beachvolleykenttä') {
      return 15, 30
    }
    else {
      return 15, 30
    }
  }

  getUserLocation = () => {

    if(navigator.geolocation)
    {

    navigator.geolocation.getCurrentPosition(position => {


        this.setState({
            userLocation: [position.coords.latitude, position.coords.longitude, position.coords.accuracy]
        })


     this.fetchPosition(this.state.userLocation);


    }, error => console.log(error.message), { 
        enableHighAccuracy: true
    });
  }

}

totop = (e) => {

  document.body.scrollTop = 0;
  document.documentElement.scrollTop = 0;
}


  MapComponent = () => {
    if(this.state.places.length > 0){
      return (            
        <Map center={this.state.position} zoom={this.state.zoom} maxZoom={18} minZoom={6}>
        <Button onClick={this.totop} style={{zIndex:999, position:"absolute", left:50,top:17}} >Valikko</Button>
            <TileLayer
              url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
              attribution="&copy; <a href=&quot;http://osm.org/copyright&quot;>OpenStreetMap</a> contributors"
            />
            {this.state.places.map((kohde) => (
                <Marker key={'key' + kohde.lat + kohde.lon + Math.random()} onClick={() => this.fetchWeather(kohde.lat, kohde.lon)} position={[kohde.lat, kohde.lon]} icon={
                    new L.Icon({
                        iconUrl: require('../img/green-icon.png'),
                        iconSize: new L.Point(this.iconSize(kohde.typeName)),
                    })
                }>
                    <Popup autoClose={false} maxWidth={1000}>
                        <div>
                          <h1>{kohde.name}</h1>
                          <p>{kohde.typeName}</p>
                          <p>Osoite: {kohde.address}</p>
                          <p>Paikkakunta: {kohde.city}, {kohde.cityPart}</p>
                          <p>Puhnro: {kohde.phone}</p>
                          <p>S-posti: {kohde.email}</p>
                          <p className="text-justify">WWW: <a href={kohde.www}>{kohde.www}</a></p>

                          <h3>Sää</h3>
                          <p>{this.state.weather.desc}</p>
                          <p>{this.state.weather.icon}</p>
                          <p>{this.state.weather.temp}</p>
                          <p>{this.state.weather.wind}</p>
                        </div>
                    </Popup>
                </Marker>
              ))}
              {this.state.sijaintisi.map((kohde2) => (
                <Marker key={Math.random()} position={this.state.sijaintisi} icon={
                    new L.Icon({
                      iconUrl: require('../img/red-icon.png'),
                      iconSize: new L.Point(this.iconSize("red-icon.png"))

                    })
                }>

                    <Popup><h1>Sijaintisi</h1></Popup>

                </Marker>

              ))}
          </Map>
      )
    }
    else {
      return (

        <Map center={position} zoom={7} maxZoom={18} minZoom={6}>
          <Button onClick={this.totop} style={{zIndex:999, position:"absolute", left:50,top:17}} >Valikko</Button>
            <TileLayer
              url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
              attribution="&copy; <a href=&quot;http://osm.org/copyright&quot;>OpenStreetMap</a> contributors"
            />

              {this.state.sijaintisi.map((kohde2) => (
                <Marker key={Math.random()} position={this.state.sijaintisi} icon={
                    new L.Icon({
                      iconUrl: require('../img/red-icon.png'),
                      iconSize: new L.Point(this.iconSize("red-icon.png"))

                    })
                }>

                    <Popup><h1>Sijaintisi</h1></Popup>

                </Marker>

              ))}
          </Map>
      )
    }
  }

  render() {
      return (
          <div id="mapid" className="h-100 w-100">

            <this.MapComponent />
          </div>

      )
  }
}

export default Kartta;
0 Answers
Related