简体   繁体   中英

React-leaflet: Map and marker are not centered

I am using react-leaflet to display a latLng position as a marker on this map, using OSM (open-street-maps). Following the basic example of the react-leaflet docs , my marker and the center of my map, always are aligned in the top-left corner of the map.

I want the map to be centered so that the marker is in the center of the map-surrounding box, but it seems not to work.

Does anyone have an idea?

The answer to my problem

What I have missed

Actually I could find out what the issue was. Similar to other issues on StackOverflow on exactly that topic, it had something to do with a modal animation ( an information, I probably missed to mention in my question ).

However, the modal which contained the map, takes round about one second to animate (simple from-left-to-right-flow animation). The map itself, starts rendering as soon as the modal gets rendered (reacts rendering mechanism handles that for me) - so the map gets rendered just as soon as the modal appears on the screen, but way smaller than the size it is going to animate to.

At this point, the map renders only the visible part - which is about 20% of the required end-size.

My solution

The modal uses the spring library to animate. The library offers callback functions that are ran as soon as the animation starts and when it ends. Because I din't want to set up a new context for it, I decided to use an already existing redux state for the modal - which I updated with a flag animationEnded - which defaults to false . Whenever the modal opens and stops it's animation, the flag gets updated.

In my component where I render my map in, I use a redux store-hook to wait on the modal animation to end - meanwhile I display a loading indicator.

As soon as the animation stops, I let react render the map.

Conclusion

I had to make sure that the animation really stopped before I start rendering the map - so solutions like "setTimeout" were not a fit for me at all (aside it being bad code - some browser may take longer for rendering and some may be faster and also "setTimeout" doesn't really wait but rather waits until the event loop lets it run). To my luck, the modal component offered a way to let me know when the animation ends.

I hope that this will help others in the future.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM