Using Maps in your Express app with Leaflet.js
You can find the sample working code here
For simplicity we'll just use CDN links to set up leaflet in your project. You can also read the docs here
Add this your respective .hbs
file or the layout.hbs
file in the <head>
tag.
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" />
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>
Wherever you want to show a map to the user , create an empty <div>
for the map to be rendered within the <div>
<div id="mapid"></div>
We've used mapid
as the id
attribute of the element, but the name is not important, you can choose any sensible id
value
#mapid {
height: 380px;
}
<script>
const map = L.map('mapid').setView([51.505, -0.09], 13);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
L.marker([51.5, -0.09]).addTo(map)
.bindPopup('This is my pop up<br> Easily customizable.')
</script>
Once you've installed/set up leaflet, it make a global object L
available to us which is the leaflet object with lots of properties and methods
The line L.map('mapid')
set's up your map with an element with an id mapid
You can find a much more detailed explanation here as well
Now you should be able to see a map
While passing variables to your hbs
file ensure you JSON.stringify
the variables you want the map to use
router.get("/", (req, res, next) => {
let loc = [51.505, -0.09]
res.render("index.hbs", {loc: JSON.stringify(loc)});
});
Now in your hbs
file you can access the loc
variable in the script tag this way
<script>
console.log( {{{loc}}} ) // prints [51.505, -0.09]
</script>
to access any variable passed from handlebars we need to use the quotes and three curly opening/closing brackets
"{{{ VARIABLE }}}"
Since we use the quotes, we ensure that we stringify
the data while sending from the route and parse it in your .hbs
<script>
tag to preserve the original data type and encoding
Happy coding! ❤️