Leaflet makes creating maps in the browser dead simple. With some HTML and 3 lines of JavaScript, we can quickly have a map displaying.
[00:01] LeafletJS is a really powerful, yet simple mapping library that has essentially become the de facto standard in mapping on the web.
[00:11] To illustrate how simple the code can be, we have imported the Leaflet CSS in JavaScript. We've created a div with an ID of map that we're going to build our map into.
[00:21] Then, we have three lines of code here to create our map. We're going to say, "L," which is Leaflet, ".map." Give it the name of our element to create it inside of, and then call setView, and then, give it a coordinate pair which is just lat and long, and then, a zoom level.
[00:38] The next line is the URL to our tile provider, which in this case is OpenStreetMaps. You can see that there are a couple of placeholders in this URL. All you really need to know is that's the format that Leaflet uses. The Z, X, and Y just stand for zoom and then the X and Y coordinates.
[01:00] Lastly, we call L.tilelayer, because the mapping tiles are a tile layer. There's other types of layers in Leaflet. Then, we tell it to add it to our map.
[01:12] We can see here we've got a nice view of the United States. We can zoom way out until the map actually starts to loop. We can also zoom way, way in to get all the way down to the street level.
[01:26] One thing to note is that when you see the map zooming in and out without the button there it's actually responding to the scroll wheel. It will do that automatically. It also works for pinch and zoom on mobile devices.
[01:42] You see there that we have created the simplest possible map in essentially three lines of code. Just to show you a couple more options here what we can actually do is go into the this call to tile layer and give it some options that we want it to set up for us.
[02:00] There's a whole host of options but for this example we're going to look at a couple that will limit the zoom for us. We're going to say the minimum zoom is three and the maximum zoom is 10.
[02:12] The minimum zoom will keep us from zooming out so far that we start to see multiple copies of continents and things like that. The maximum zoom will prevent us from getting down to the street level.
[02:23] That's as far out as we can get on zooming out. We've got the zoom out button as disabled there for us, because it knows we're at the max. Then if we zoom in, our maximum zoom is going to stop us right here.
[02:39] We can see all the many, many airports in this area. That's weird. We can no longer zoom in once we get to that max zoom level.
[02:49] Just to show you an alternative, we're going to put in some different lat and long coordinates in the closer zoom level. Then, we'll get rid of our options here. We can see that when we refresh the page we actually are taken out and see London.
[03:08] It's very easy to set the location of the map initially to whatever you may need.