I am building a project that locates IP address with Ipify and Leaflet API's with VITE. I couldn't get the map functions such as (panTo, flyTo and so on) to work so i started a completely clean project to check if i messed something up. What I have found is that by pasting the leaflet map initialization directly in console - works flawlessly , functions are available.
But when I use the main.js it does not , map.panTo() is not there ... What am I missing ?
main.js below - map has been initialized as described in API
let map = L.map("map").setView([51.505, -0.09], 13);
L.tileLayer("https://tile.openstreetmap.org/{z}/{x}/{y}.png", {
maxZoom: 19,
attribution:
'© <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>',
}).addTo(map);
INDEX.HTML below
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bootstrap w/ Vite</title>
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css"
integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=" crossorigin="" />
<link rel="stylesheet" href="/scss/styles.css">
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"
integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo=" crossorigin=""></script>
<script type="module" src="./js/main.js"></script>
</head>
<body>
<div class="container py-4 px-3 mx-auto">
<h1>Hello, Bootstrap and Vite!</h1>
<button class="btn btn-primary">Primary button</button>
</div>
<div id="map" class="bg-body-secondary"></div>
</body>
</html>
I have tried placing the script leaflet.js tags in head, at the end of the body, tried importing in main.js from https://unpkg.com/[email protected]/dist/leaflet.js, with {} or with { map } did not work.
I tried looking for a solution on the web and most of the problems that have occured for other devs are because of declaring map in function which keeps its scope local.
I think mine should be global ? I am completely clueless right now.. Please help
I need functionality of map.panTo to pan the map with results of other API answer .
You can do it like this, if you want to keep your main.js
as a module.
const btnPan = document.querySelector(".btn.btn-primary");
const spanCoordinates = document.querySelector("#coordinates");
const sunIcon = L.icon({
iconUrl: 'https://www.svgrepo.com/show/434342/sun.svg',
iconSize: [30, 30], // size of the icon
iconAnchor: [30, 30], // point of the icon which will correspond to marker's location
popupAnchor: [-3, -76], // point from which the popup should open relative to the iconAnchor
});
btnPan.addEventListener("click",function() {
// random lat-lng
let latRand = Math.random(-1,1)*90;
let lngRand = Math.random(-1,1)*90;
// move to the new location
map.panTo([latRand,lngRand]);
// remove the old marker (if there was one to begin with)
let markerIcon = document.querySelector(".leaflet-marker-icon");
if(markerIcon) {
markerIcon.remove();
}
let markerPopup = document.querySelector(".leaflet-popup");
if(markerPopup) {
markerPopup.remove();
}
// add a new marker to the map
let marker = [latRand,lngRand];
L.marker(marker, {icon: sunIcon}).addTo(map);
spanCoordinates.innerText = `We are now at: ${latRand} lat, ${lngRand} lng`;
});
h1 {
margin-top: 0px;
margin-bottom: 0px;
}
#coordinates {
display: inline
}
#map {
height: 350px;
}
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css"
integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=" crossorigin="" />
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"
integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo=" crossorigin=""></script>
<!-- I'm deliberately declaring the map variable here, so that it can be accessed later on -->
<script>let map;</script>
<!--
Your original file is used here for demonstration purposes.
You can use it as an external file, as you indented
-->
<script type="module">
// just assigning a value to our map variable
map = L.map("map").setView([51.505, -0.09], 13);
L.tileLayer("https://tile.openstreetmap.org/{z}/{x}/{y}.png", {
maxZoom: 19,
attribution:
'© <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>',
}).addTo(map);
</script>
<div class="container py-4 px-3 mx-auto">
<h1>Hello, Bootstrap and Vite!</h1>
<button class="btn btn-primary">Primary button</button>
<!-- The span element below is just for info, to let us know where we are after clicking -->
<span id="coordinates"></span>
</div>
<div id="map" class="bg-body-secondary"></div>
The code contains some JS parts which were put there simply for demo purposes (button click event handler, markers on the map, randomization when panning, etc).
The key was in moving the map
outside of your module, i.e. making it global. That way you can add other things you mentioned (panning to coordinates returned to you by the API call to Ipify, or some other service).