0

I am building a webapp with Sveltekit that uses leaflet to show different shipments but when i first load the /shipment/id page the map is displayed incorrectly. Zooming in i also noticed that the popup messages are not working and the route is completely missing:

Leaflet wrong map

Meanwhile i refresh the page the map is shown normally:

Leaflet correct map

This is the code i am using:

+page.svelte

<script>
import {onMount} from 'svelte';
import {show_map} from './shipment.js';
onMount(() => {
    show_map(data.shipment_details);
}); 
</script>

<div id="map"></div>

shipment.js

export function show_map(query_output) {

let start_coordinates = JSON.parse(query_output.start_point).coordinates;

let end_coordinates = JSON.parse(query_output.end_point).coordinates;

let start_route = {"type":"Point","coordinates":[start_coordinates[0], start_coordinates[1]]};

let end_route = {"type":"Point","coordinates":[end_coordinates[0], end_coordinates[1]]};

let bounds = L.latLngBounds(L.latLng(start_coordinates[1], start_coordinates[0]), L.latLng(end_coordinates[1], end_coordinates[0]));

let map = L.map('map', {zoomControl: false}).fitBounds(bounds);

L.control.zoom({position: 'topright'}).addTo(map);

let Jawg_Streets = L.tileLayer('map', {
    attribution: 'attribution',
    minZoom: 0,
    maxZoom: 22,
    subdomains: 'abcd',
    accessToken: 'token'
})

Jawg_Streets.addTo(map);

let myStyle = {
    "color": "red",
    "weight": 10,
    "opacity": 0.65
};

L.geoJSON(JSON.parse(query_output.route), {style: myStyle}).addTo(map);

L.geoJSON(start_route).addTo(map).bindPopup("Start warehouse");

L.geoJSON(end_route).addTo(map).bindPopup("End warehouse");

}

How can show the map correctly on first load? I also add that currently the leaflet .js and .css files are loaded throught the CDN in the app.html file.

pydev95
  • 89
  • 1
  • 8
  • Run `invalidateSize()` after mount. – IvanSanchez Jan 15 '23 at 18:48
  • After some tests it looked like the problem was related to the css stylesheet i imported. WIthout it the map loaded correctly. In order to keep my styles and load the map correctly i moved the width and height properties of the map and its container inline in the elements and now everything works. – pydev95 Jan 16 '23 at 20:37

0 Answers0