Skip to content

Instantly share code, notes, and snippets.

@ManishPoduval
Last active April 22, 2021 08:09
Show Gist options
  • Save ManishPoduval/061bfb6c1cc4d86c6cc9e07a6a5bc5b0 to your computer and use it in GitHub Desktop.
Save ManishPoduval/061bfb6c1cc4d86c6cc9e07a6a5bc5b0 to your computer and use it in GitHub Desktop.

Using Maps in your Express app with Leaflet.js

You can find the sample working code here

Installation

1. Set up Leaflet css/js files

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>


2. Add the map to your hbs file

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 mapidas the id attribute of the element, but the name is not important, you can choose any sensible id value

Add a height / width css properties to your div

#mapid { 
	height: 380px; 
}

Add this script tag in the same hbs file where the div was added so that it loads the map

<script>
	const map = L.map('mapid').setView([51.505, -0.09], 13);

	L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
	attribution: '&copy; <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

Bonus

Passing dynamic variables to your map <script>

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! ❤️

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment