Reputation: 59
My website has Mapbox maps for golf course locations.
Here's an example page, scroll down to see the map: https://www.golfscout.net/golf-course/harborside-international-golf-center-port-course-chicago-illinois
Problem: On Chrome desktop, the map often (not always) only shows for half the space of the div, making it look cut off. Here's a screenshot of what that looks like: https://www.golfscout.net/images/mapbox-half-map.jpg
This is using Mapbox GL JS v2.13.0.
I thought map reload call would fix it, but it doesn't:
map.on('load', function () {
map.resize();
});
It generally seems to work okay on Safari and Firefox. Any ideas? Thanks!
Here's the full map code:
mapboxgl.accessToken = '<token>';
const map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v12',
center: [-87.588567551718, 41.694580079560],
zoom: 10
});
const marker = new mapboxgl.Marker()
.setLngLat([-87.588567551718, 41.694580079560])
.addTo(map);
map.addControl(new mapboxgl.FullscreenControl());
map.addControl(new mapboxgl.NavigationControl());
map.on('load', function () {
map.resize();
});
Upvotes: 1
Views: 1349
Reputation: 1
2024, for react using lodash.debounce
useEffect(() => {
const debouncedResize = debounce(() => {
mapRef.current?.resize();
}, 0);
const handleResize = () => {
debouncedResize();
};
const resizer = new ResizeObserver(handleResize);
if (mapContainerRef.current) {
resizer.observe(mapContainerRef.current);
}
return () => {
resizer.disconnect();
debouncedResize.cancel();
};
}, []);
Upvotes: 0
Reputation: 21
was fixed for me triggering the window resize on map load (chrome and safari at least):
map.on("load", () => {window.dispatchEvent(new Event("resize"));});
Upvotes: 1
Reputation: 1
To whom it may concern, I went through the same situation in an ionic project with Angular. The solution was to initialize the map inside an ionViewDidEnter() code block:
ionViewDidEnter(): void {
this.initializeMap();
}
initializeMap(): void {
mapboxgl.accessToken = 'YOUR_MAPBOX_TOKEN';
var map = new mapboxgl.Map({
container: 'YOUR_MAP_CONTAINER',
style: 'mapbox://styles/mapbox/streets-v11',
center: [-0, 0],
zoom: 10
});
}
Upvotes: 0
Reputation: 1435
When I load your page, the map loads with that height initially then the container dynamically increases in height after the images around it load.
The best option is to set the map at the correct height from the start, just set a height that matches the image displayed next to it, or put the map on its own row.
If you really want to use map.resize()
You'll need to fire it after the image loads, something like
let img = document.querySelector('#id-of-image-next-to-map');
img.addEventListener('load', (event) => {
map.resize()
});
Upvotes: 0