Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

web development
maps
leaflet.js

How to use Leaflet.js to integrate maps in JavaScript

Educative Answers Team

Leaflet.js is an open-source JavaScript library that helps you easily integrate maps in your web-application.

In this shot, we will look at how to set up a map and add different types of markers and shapes into a web application. The Leaflet library contains many more plugins that can be included in your project to add functionalities to your map. However, we won’t be talking about those additional functionalities in this shot.

The integration of the map is effortless. All you need to do is add the following two tags in your HTML file’s head tag. Make sure to write these two tags in the same order as shown below for it to work.

<link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css"
integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A=="
crossorigin=""/>
<script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"
integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA=="
crossorigin=""></script>

Next, you need to create a div in your HTML file with a specific id. Make sure that this div has a defined height.

<div id="mapid"></div>

Now, we need to set up a map using the setView() function. This function takes two input parameters: the geographical coordinates and the zoom level.

After that, we need to add a tileLayer() and addTo() function to our map.

The code should look like:

var mymap = L.map('mapid').setView([51.505, -0.09], 13);

L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
  attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(mymap);

The following are codes used to add different types of markers and shapes to your map.

//marker
var marker = L.marker([51.5, -0.09]).addTo(mymap);

//circle
var circle = L.circle([51.508, -0.11], {
    color: 'red',
    fillColor: '#f03',
    fillOpacity: 0.5,
    radius: 500
}).addTo(mymap);

//polygon
var polygon = L.polygon([
    [51.509, -0.08],
    [51.503, -0.06],
    [51.51, -0.047]
]).addTo(mymap);

Below is a running example of a map integrated into a web-application using Leaflet.

RELATED TAGS

web development
maps
leaflet.js
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring