Leaflet Tutorial – Overlay

Leaflet Tutorial – Overlay – Brilliansolution. Instead of map overlays, you can also use image, video overlays in a Leaflet application. In this chapter, we will see how to use such overlays.

Contents
Image Overlay
Follow the steps given below to use an image overlay.
Step 1 − Create a Map object by passing a <div> element (String or object) and map options (optional).
Step 2 − Create a Layer object by passing the URL of the desired tile.
Step 3 − Add the layer object to the map using the addLayer() method of the Map class.
Step 4 − Create the image overlay using L.imageOverlay(). Pass the URL of the image and an object representing image bounds, as shown below.
// Creating Image overlay var imageUrl = 'tpPoster.jpg'; var imageBounds = [[17.342761, 78.552432], [16.396553, 80.727725]]; var overlay = L.imageOverlay(imageUrl, imageBounds);
Step 5 − Add the overlay to the map using addTo() method of the imageOverlay class, as shown below.
// Adding overlay to the map overlay.addTo(map);
Example
The following code demonstrates the usage of image overlay.
<!DOCTYPE html>
<html>
<head>
<title>Image Overlay Example</title>
<link rel = "stylesheet" href = "http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css"/>
<script src = "http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
</head>
<body>
<div id = "map" style = "width:900px; height:580px"></div>
<script>
// Creating map options
var mapOptions = {
center: [17.342761, 78.552432],
zoom: 8
}
var map = new L.map('map', mapOptions); // Creating a map object
// Creating a Layer object
var layer = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png');
map.addLayer(layer); // Adding layer to the map
// Creating Image overlay
var imageUrl = 'tpPoster.jpg';
var imageBounds = [[17.342761, 78.552432], [16.396553, 80.727725]];
var overlay = L.imageOverlay(imageUrl, imageBounds);
overlay.addTo(map);
</script>
</body>
</html>
Overlays
There are 3 overlays in the Leaflet API:
ImageOverlay
: Raster Layer, ExtendsLayer
VideoOverlay
: Raster Layer, ExtendsImageOverlay
SVGOverlay
: Vector Layer, ExtendsImageOverlay
In this tutorial, you’ll learn how to use these overlays.
ImageOverlay
L.ImageOverlay
is used to load and display a single image over specific bounds of the map.
To add an image overlay L.ImageOverlay
use this:
var imageOverlay = L.imageOverlay(imageUrl, latLngBounds, options);
Creating a map
First of all, create a Leaflet map and add a background L.TileLayer
in the usual way:
var map = L.map('map').setView([37.8, -96], 4);
var osm = L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 19,
attribution: '© <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
}).addTo(map);
Let’s create an image overlay with multiple options:
var imageUrl = 'https://maps.lib.utexas.edu/maps/historical/newark_nj_1922.jpg';
var errorOverlayUrl = 'https://cdn-icons-png.flaticon.com/512/110/110686.png';
var altText = 'Image of Newark, N.J. in 1922. Source: The University of Texas at Austin, UT Libraries Map Collection.';
var latLngBounds = L.latLngBounds([[40.799311, -74.118464], [40.68202047785919, -74.33]]);
var imageOverlay = L.imageOverlay(imageUrl, latLngBounds, {
opacity: 0.8,
errorOverlayUrl: errorOverlayUrl,
alt: altText,
interactive: true
}).addTo(map);
If you want to see the area which is covered by the ImageOverlay, you can add a L.Rectangle
with the same L.LatLngBounds
to the map:
L.rectangle(latLngBounds).addTo(map);
map.fitBounds(latLngBounds);
opacity
defines the opacity of the image overlay, it equals to1.0
by default. Decrease this value to make an image overlay transparent and to expose the underlying map layer.errorOverlayUrl
is a URL to the overlay image to show in place of the overlay that failed to load.alt
sets the HTMLalt
attribute to provide an alternative text description of the image. Alternative text is essential information for screen reader users. It can also benefit people during poor network connectivity, in the case the image fails to load. Moreover, it can improve the SEO of a website.interactive
isfalse
by default. Iftrue
, the image overlay will emit mouse events when clicked or hovered.
You can find other options of L.ImageOverlay
in the documentation.
https://leafletjs.com/examples/overlays/example-image.html |
See this example stand-alone. |
VideoOverlay
Video used to be a hard task when building a webpage, until the <video>
HTML element was made available.
Nowadays, we can use the following HTML code:
<video width="500" controls>
<source src="https://www.mapbox.com/bites/00188/patricia_nasa.webm" type="video/webm">
<source src="https://www.mapbox.com/bites/00188/patricia_nasa.mp4" type="video/mp4">
</video>
To display this video:
If a video can be shown in a webpage in this way, then Leaflet can display it inside a map. It is important that the videos are prepared in such a way that they will fit the map: The video should have a “north-up” orientation, and its proportions should fit the map. If not, it will look out of place.
Creating a map
First of all, create a Leaflet map and add a background L.TileLayer
in the usual way:
var map = L.map('map').setView([37.8, -96], 4);
var osm = L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 19,
attribution: '© <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
}).addTo(map);
Adding the video overlay
Adding a video overlay works very similar to adding an image overlay.
For a video overlay, just:
- Use
L.VideoOverlay
instead ofL.ImageOverlay
L.VideoOverlay
is used to load and display a video player over specific bounds of the map. ExtendsL.ImageOverlay
. A video overlay uses the<video>
HTML element.- Instead of the image URL, specify one video URL or an array of video URLs
var videoUrls = [
'https://www.mapbox.com/bites/00188/patricia_nasa.webm',
'https://www.mapbox.com/bites/00188/patricia_nasa.mp4'
];
var errorOverlayUrl = 'https://cdn-icons-png.flaticon.com/512/110/110686.png';
var latLngBounds = L.latLngBounds([[32, -130], [13, -100]]);
var videoOverlay = L.videoOverlay(videoUrls, latLngBounds, {
opacity: 0.8,
errorOverlayUrl: errorOverlayUrl,
interactive: true,
autoplay: true,
muted: true,
playsInline: true
}).addTo(map);
And just like that, you’ll get the video on your map:
https://leafletjs.com/examples/overlays/example-nocontrols.html |
See this example stand-alone. |
autoplay
option defines whether the video starts playing automatically when loaded. It istrue
by default. It is important to know that on some browsersautoplay
functionality will only work withmuted
option explicitly set totrue
.muted
option defines whether the video starts on mute when loaded. It isfalse
by default.playsInline
option when it is set totrue
allows video to play inline without automatically entering fullscreen mode when playback begins in the mobile browser. It istrue
by default.
You can find other options of L.videoOverlay
in the documentation.
Video overlays behave like any other Leaflet layer – you can add and remove them, let the user select from several videos using a layers control, etc.
A bit of control over the video
If you read the API documentation, you’ll notice that the L.VideoOverlay
class does not have a play()
or pause()
method.
For this, the getElement()
method of the video overlay is useful. It returns the HTMLVideoElement
(which inherits from HTMLMediaElement
) for the overlay – and that has methods like play()
and pause()
, e.g.
videoOverlay.getElement().pause();
This allows us to build custom interfaces. For example, we can build a small subclass of L.Control
to play/pause this video overlay once it’s loaded:
videoOverlay.on('load', function () {
var MyPauseControl = L.Control.extend({
onAdd: function() {
var button = L.DomUtil.create('button');
button.title = 'Pause';
button.innerHTML = '<span aria-hidden="true">⏸</span>';
L.DomEvent.on(button, 'click', function () {
videoOverlay.getElement().pause();
});
return button;
}
});
var MyPlayControl = L.Control.extend({
onAdd: function() {
var button = L.DomUtil.create('button');
button.title = 'Play';
button.innerHTML = '<span aria-hidden="true">▶️</span>';
L.DomEvent.on(button, 'click', function () {
videoOverlay.getElement().play();
});
return button;
}
});
var pauseControl = (new MyPauseControl()).addTo(map);
var playControl = (new MyPlayControl()).addTo(map);
});
https://leafletjs.com/examples/overlays/example-video.html |
See this example stand-alone. |
SVGOverlay
L.SVGOverlay
is used to load, display and provide DOM access to an SVG file over specific bounds of the map.
To add an SVG overlay L.SVGOverlay
use this:
var svgOverlay = L.svgOverlay(SVGElement, svgElementBounds, options);
It instantiates an image overlay object given an SVG element and the geographical bounds it is tied to. A viewBox attribute is required on the SVG element to zoom in and out properly.
Creating an SVG element
Let’s create an SVG element:
var svgElement = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svgElement.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
svgElement.setAttribute('viewBox', '0 0 200 200');
svgElement.innerHTML = '<rect width="200" height="200"/><rect x="75" y="23" width="50" height="50" style="fill:red"/><rect x="75" y="123" width="50" height="50" style="fill:#0013ff"/>';
Alternatively, you can create the SVG element in HTML code:
<svg id="svg" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200"><rect width="200" height="200"/><rect x="75" y="23" width="50" height="50" style="fill:red"/><rect x="75" y="123" width="50" height="50" style="fill:#0013ff"/></svg>
And choose this SVG element by using a querySelector:
var svgElement = document.querySelector('#svg');
Adding the SVG overlay
Create the SVGOverlay with desired options similarly to ImageOverlay and VideoOverlay:
var latLngBounds = L.latLngBounds([[32, -130], [13, -100]]);
map.fitBounds(latLngBounds);
var svgOverlay = L.svgOverlay(svgElement, latLngBounds, {
opacity: 0.7,
interactive: true
}).addTo(map);
Although SVGOverlay does not have its own unique options, it inherits a variety of options from ImageOverlay, Interactive layer and Layer. Check out the documentation to find out more L.SVGOverlay
options.
https://leafletjs.com/examples/overlays/example-svg.html |
See this example stand-alone. |
DivOverlay
Base model for L.Popup and L.Tooltip. Inherit from it for custom overlays like plugins.
Options
Option | Type | Default | Description |
---|---|---|---|
interactive | Boolean | false | If true, the popup/tooltip will listen to the mouse events. |
offset | Point | Point(0, 0) | The offset of the overlay position. |
className | String | '' | A custom CSS class name to assign to the overlay. |
pane | String | undefined | Map pane where the overlay will be added. |
content | String|HTMLElement|Function | '' | Sets the HTML content of the overlay while initializing. If a function is passed the source layer will be passed to the function. The function should return a String or HTMLElement to be used in the overlay. |
▶ Options inherited from Interactive layer▶ Options inherited from Layer
Events
DivOverlay events
Event | Data | Description |
---|---|---|
contentupdate | Event | Fired when the content of the overlay is updated |
▶ Mouse events inherited from Interactive layer▶ Events inherited from Layer▶ Popup events inherited from Layer▶ Tooltip events inherited from Layer
Methods
Method | Returns | Description |
---|---|---|
openOn(<Map> map) | this | Adds the overlay to the map. Alternative to map.openPopup(popup) /.openTooltip(tooltip) . |
close() | this | Closes the overlay. Alternative to map.closePopup(popup) /.closeTooltip(tooltip) and layer.closePopup() /.closeTooltip() . |
toggle(<Layer> layer?) | this | Opens or closes the overlay bound to layer depending on its current state. Argument may be omitted only for overlay bound to layer. Alternative to layer.togglePopup() /.toggleTooltip() . |
getLatLng() | LatLng | Returns the geographical point of the overlay. |
setLatLng(<LatLng> latlng) | this | Sets the geographical point where the overlay will open. |
getContent() | String|HTMLElement | Returns the content of the overlay. |
setContent(<String|HTMLElement|Function> htmlContent) | this | Sets the HTML content of the overlay. If a function is passed the source layer will be passed to the function. The function should return a String or HTMLElement to be used in the overlay. |
getElement() | String|HTMLElement | Returns the HTML container of the overlay. |
update() | null | Updates the overlay content, layout and position. Useful for updating the overlay after something inside changed, e.g. image loaded. |
isOpen() | Boolean | Returns true when the overlay is visible on the map. |
bringToFront() | this | Brings this overlay in front of other overlays (in the same map pane). |
bringToBack() | this | Brings this overlay to the back of other overlays (in the same map pane). |
▶ Methods inherited from Layer▶ Popup methods inherited from Layer▶ Tooltip methods inherited from Layer▶ Methods inherited from Evented
ImageOverlay
Used to load and display a single image over specific bounds of the map. Extends Layer
.
Usage example
var imageUrl = 'https://maps.lib.utexas.edu/maps/historical/newark_nj_1922.jpg',
imageBounds = [[40.712216, -74.22655], [40.773941, -74.12544]];
L.imageOverlay(imageUrl, imageBounds).addTo(map);
Creation
Factory | Description |
---|---|
L.imageOverlay(<String> imageUrl, <LatLngBounds> bounds, <ImageOverlay options> options?) | Instantiates an image overlay object given the URL of the image and the geographical bounds it is tied to. |
Options
Option | Type | Default | Description |
---|---|---|---|
opacity | Number | 1.0 | The opacity of the image overlay. |
alt | String | '' | Text for the alt attribute of the image (useful for accessibility). |
interactive | Boolean | false | If true , the image overlay will emit mouse events when clicked or hovered. |
crossOrigin | Boolean|String | false | Whether the crossOrigin attribute will be added to the image. If a String is provided, the image will have its crossOrigin attribute set to the String provided. This is needed if you want to access image pixel data. Refer to CORS Settings for valid String values. |
errorOverlayUrl | String | '' | URL to the overlay image to show in place of the overlay that failed to load. |
zIndex | Number | 1 | The explicit zIndex of the overlay layer. |
className | String | '' | A custom class name to assign to the image. Empty by default. |
▶ Options inherited from Interactive layer▶ Options inherited from Layer
Events
Event | Data | Description |
---|---|---|
load | Event | Fired when the ImageOverlay layer has loaded its image |
error | Event | Fired when the ImageOverlay layer fails to load its image |
▶ Mouse events inherited from Interactive layer▶ Events inherited from Layer▶ Popup events inherited from Layer▶ Tooltip events inherited from Layer
Methods
Method | Returns | Description |
---|---|---|
setOpacity(<Number> opacity) | this | Sets the opacity of the overlay. |
bringToFront() | this | Brings the layer to the top of all overlays. |
bringToBack() | this | Brings the layer to the bottom of all overlays. |
setUrl(<String> url) | this | Changes the URL of the image. |
setBounds(<LatLngBounds> bounds) | this | Update the bounds that this ImageOverlay covers |
setZIndex(<Number> value) | this | Changes the zIndex of the image overlay. |
getBounds() | LatLngBounds | Get the bounds that this ImageOverlay covers |
getElement() | HTMLElement | Returns the instance of HTMLImageElement used by this overlay. |
getCenter() | LatLng | Returns the center of the ImageOverlay. |
▶ Methods inherited from Layer▶ Popup methods inherited from Layer▶ Tooltip methods inherited from Layer▶ Methods inherited from Evented
VideoOverlay
Used to load and display a video player over specific bounds of the map. Extends ImageOverlay
.
A video overlay uses the <video>
HTML5 element.
Usage example
var videoUrl = 'https://www.mapbox.com/bites/00188/patricia_nasa.webm',
videoBounds = [[ 32, -130], [ 13, -100]];
L.videoOverlay(videoUrl, videoBounds ).addTo(map);
Creation
Factory | Description |
---|---|
L.videoOverlay(<String|Array|HTMLVideoElement> video, <LatLngBounds> bounds, <VideoOverlay options> options?) | Instantiates an image overlay object given the URL of the video (or array of URLs, or even a video element) and the geographical bounds it is tied to. |
Options
Option | Type | Default | Description |
---|---|---|---|
autoplay | Boolean | true | Whether the video starts playing automatically when loaded. On some browsers autoplay will only work with muted: true |
loop | Boolean | true | Whether the video will loop back to the beginning when played. |
keepAspectRatio | Boolean | true | Whether the video will save aspect ratio after the projection. Relevant for supported browsers. See browser compatibility |
muted | Boolean | false | Whether the video starts on mute when loaded. |
playsInline | Boolean | true | Mobile browsers will play the video right where it is instead of open it up in fullscreen mode. |
▶ Options inherited from ImageOverlay▶ Options inherited from Interactive layer▶ Options inherited from Layer
Events
Event | Data | Description |
---|---|---|
load | Event | Fired when the video has finished loading the first frame |
▶ Events inherited from ImageOverlay▶ Mouse events inherited from Interactive layer▶ Events inherited from Layer▶ Popup events inherited from Layer▶ Tooltip events inherited from Layer
Methods
Method | Returns | Description |
---|---|---|
getElement() | HTMLVideoElement | Returns the instance of HTMLVideoElement used by this overlay. |
▶ Methods inherited from ImageOverlay▶ Methods inherited from Layer▶ Popup methods inherited from Layer▶ Tooltip methods inherited from Layer▶ Methods inherited from Evented
SVGOverlay
Used to load, display and provide DOM access to an SVG file over specific bounds of the map. Extends ImageOverlay
.
An SVG overlay uses the <svg>
element.
Usage example
var svgElement = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svgElement.setAttribute('xmlns', "http://www.w3.org/2000/svg");
svgElement.setAttribute('viewBox', "0 0 200 200");
svgElement.innerHTML = '<rect width="200" height="200"/><rect x="75" y="23" width="50" height="50" style="fill:red"/><rect x="75" y="123" width="50" height="50" style="fill:#0013ff"/>';
var svgElementBounds = [ [ 32, -130 ], [ 13, -100 ] ];
L.svgOverlay(svgElement, svgElementBounds).addTo(map);
Creation
Factory | Description |
---|---|
L.svgOverlay(<String|SVGElement> svg, <LatLngBounds> bounds, <SVGOverlay options> options?) | Instantiates an image overlay object given an SVG element and the geographical bounds it is tied to. A viewBox attribute is required on the SVG element to zoom in and out properly. |
Options
▶ Options inherited from ImageOverlay▶ Options inherited from Interactive layer▶ Options inherited from Layer
Events
▶ Events inherited from ImageOverlay▶ Mouse events inherited from Interactive layer▶ Events inherited from Layer▶ Popup events inherited from Layer▶ Tooltip events inherited from Layer
Methods
Method | Returns | Description |
---|---|---|
getElement() | SVGElement | Returns the instance of SVGElement used by this overlay. |
▶ Methods inherited from ImageOverlay▶ Methods inherited from Layer▶ Popup methods inherited from Layer▶ Tooltip methods inherited from Layer▶ Methods inherited from Evented
Source : https://leafletjs.com/
keywords :
- Leaflet Tutorial Beginer – Leaflet Marker
- leaflet marker
- leaflet markercluster
- leaflet custom marker
- react leaflet marker
- maps marker pro
- leaflet multiple markers
- leaflet maps marker
- custom marker leaflet
- leaflet filter markers
- marker react leaflet
- mapsmarker leaflet
- text marker
- wordpress leaflet maps marker
- leaflet map multiple markers
- custom leaflet markers
- leafletmaps