Giter Club home page Giter Club logo

Comments (7)

PaulLeCam avatar PaulLeCam commented on May 20, 2024 4

Hi,

It seems to be a known issue with Leaflet, if its container size is changed or if it's not visible when the map is created. Calling map.invalidateSize() resets the map display.

Here is an example to make it work with react-bootstrap:

class MapTabs extends React.Component {
  constructor() {
    super();
    this.state = {
      key: 1
    };
  }

  onSelect(key) {
    this.setState({key});
    setTimeout(() => {
      this.refs['map' + key].getLeafletElement().invalidateSize(false);
    }, 300); // Adjust timeout to tab transition
  }

  render() {
    return (
      <TabbedArea activeKey={this.state.key} onSelect={this.onSelect.bind(this)}>
        <TabPane eventKey={1} tab='Default Tab'>
            <Map ref="map1" center={position} zoom={zoom} style={style}>
                <TileLayer
                  url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
                  attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
                  />
                <Marker position={position}>
                    <Popup>
                        <span>A pretty CSS3 popup.<br/>Easily customizable.</span>
                    </Popup>
                </Marker>
            </Map>
        </TabPane>
        <TabPane eventKey={2} tab='Map Tab'>
            <Map ref="map2" center={position} zoom={zoom} style={style}>
                <TileLayer
                  url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
                  attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
                  />
                <Marker position={position}>
                    <Popup>
                        <span>A pretty CSS3 popup.<br/>Easily customizable.</span>
                    </Popup>
                </Marker>
            </Map>
        </TabPane>
      </TabbedArea>
    );
  }
}

The trick is to control the tabs from a parent component, this way you can access the relevant <Map> via its ref, and call invalidateSize() after the tab is fully displayed. That's why there is a 300ms timeout before calling the function.
If the tabs transition has a different timing, you should adjust this timeout, making sure it's always superior or equal to the transition time, otherwise the map rendering would not be done properly.

from react-leaflet.

citizen-dror avatar citizen-dror commented on May 20, 2024 1

solution using hooks (and mobx sotre) in FunctionComponent :

parent tabs Component

interface IProps { 
    defaultKey? :string
}
export const TabsTemplate: React.FC<IProps> = observer(({defaultKey="charts"}) => {
    const [activeKey] = useState(defaultKey);
    const store = useStore();
    store.isReadyToRenderMap = false;
    return (
        <Tabs defaultActiveKey={activeKey} id="main-tabs"
            onSelect={(activeKey: any) => {
                if (activeKey === "map") {
                    //map is renderd only when tab is shown
                    store.isReadyToRenderMap = true;
                }
            }}
        >
            <Tab eventKey="charts" title={"Charts"}>
                <GroupByGraphsPanel />
            </Tab>
            <Tab eventKey="map" title={"Map"}>
                <MyMap />
            </Tab>
        </Tabs>
    )
})

child map Component

const MyMap : FunctionComponent<IProps> = observer(() => {
  const mapRef = useRef<any>();
  const store = useStore();
  const reactMapCenter = toJS(store.mapCenter);
  const WRAPPER_STYLES = { height: '500px', width: '100vw', maxWidth: '100%' };
  const didMountRef = useRef(false) 
  useEffect(() => {
    if (didMountRef.current) { 
      if (mapRef.current) {
        //mapRef.current  = true - like componentDidUpdate
        //this event is fierd when parent tab is shown - help render map 
        mapRef.current.leafletElement.invalidateSize(false);
      }
    } 
    else didMountRef.current = true
  })
  return (
    <div>
        <Map ref={mapRef}
          center={reactMapCenter}
          zoom={13}
          style={WRAPPER_STYLES}
        >
          <TileLayer
            attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
            url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
          />
          <AccidentsMarkers />
        </Map>
        {store.isReadyToRenderMap?"":""}
    </div>
  )
})

from react-leaflet.

silverpedak avatar silverpedak commented on May 20, 2024 1

To anyone struggling with the map not rendering properly when using react-leaflet with reactstrap tabs, this is what worked for me.

<MapContainer
    id="map-container"
    style={{ height: "50vh" }}
    center={[40, 20]}
    zoom={2}
  >
    <TileLayer
      attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
      url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
    />
    <ResizeMap />
  </MapContainer>```
const ResizeMap = () => {
  const map = useMap();
  const resizeObserver = new ResizeObserver(() => {
    map.invalidateSize();
  });
  const container = document.getElementById("map-container");
  resizeObserver.observe(container!);

  return null;
};

Found this stackoverflow ANSWER helpful which initially didn't work because the whenReady prop will not let you use the Map instance as described in the answer.

Instead, <MapContainer /> will pass the Map instance to it's children elements as described in the React-leaflet docs

from react-leaflet.

PaulLeCam avatar PaulLeCam commented on May 20, 2024

Hi, thanks!

I have never had this use case so I don't know what can be the exact origin, can you setup a jsbin or something showing the issue please?

from react-leaflet.

michaeljones avatar michaeljones commented on May 20, 2024

Thanks for the quick response. It is a pretty niche problem! I'll try to reproduce it for you somewhere public.

from react-leaflet.

michaeljones avatar michaeljones commented on May 20, 2024

I'm afraid I don't know how to reproduce it in an environment like jsbin as I don't know how to get react-bootstrap & react-leaflet without npm. The code required for a simple demo is below:

index.html

<!DOCTYPE html>
<html>
    <head>
        <script src="https://fb.me/react-with-addons-0.13.3.js"></script>
        <script src="https://code.jquery.com/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>

        <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet" type="text/css" />

        <!-- Leaflet Maps Styling  -->
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.3/leaflet.css">

        <meta charset="utf-8">
        <title>Tabbed Map Example</title>

    </head>
    <body>

        <div id="tab-container"></div>

        <script type="text/javascript" src="demo.js"></script>

    </body>

</html>

app.js

var React = require('react');
var TabbedArea = require('react-bootstrap/lib/TabbedArea');
var TabPane = require('react-bootstrap/lib/TabPane');
const position = [51.5072, -0.1275];
const style = { height: '400px' };
const zoom = 5;

const tabbedAreaInstance = (
  <TabbedArea defaultActiveKey={1}>
    <TabPane eventKey={1} tab='Default Tab'>
        <Map center={position} zoom={zoom} style={style}>
            <TileLayer
              url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
              attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
              />
            <Marker position={position}>
                <Popup>
                    <span>A pretty CSS3 popup.<br/>Easily customizable.</span>
                </Popup>
            </Marker>
        </Map>
    </TabPane>
    <TabPane eventKey={2} tab='Map Tab'>
        <Map center={position} zoom={zoom} style={style}>
            <TileLayer
              url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
              attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
              />
            <Marker position={position}>
                <Popup>
                    <span>A pretty CSS3 popup.<br/>Easily customizable.</span>
                </Popup>
            </Marker>
        </Map>
    </TabPane>
  </TabbedArea>
);

React.render(tabbedAreaInstance, document.getElementById('tab-container'));

browserify command

browserify app.js -t babelify --outfile demo.js

You'll need to npm install react-bootstrap, react and react-leaflet. Sorry I couldn't make it easier. Does that seem reasonable?

The demo has a set up with two tabs. I've put maps in both tabs to show that it loads properly in the default tab but when you switch to the other tab the tiles do not load properly, even when you pan around a bit it seems confused.

I'm using Chrome 43 on Ubuntu.

I hope that is sufficient but please ask if there are details I've missed.

Michael

from react-leaflet.

michaeljones avatar michaeljones commented on May 20, 2024

Wow, thank you for investigating and for the explaining. Kind of you to give such a clear run down. I will attempt to integrate this approach into my set up.

I guess I'll close this ticket as there isn't really an action point for it. It is such an edge case that it doesn't seem worth trying to add to the documentation for react-leaflet itself.

Much appreciated!

from react-leaflet.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    šŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. šŸ“ŠšŸ“ˆšŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ā¤ļø Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.