LeafletJS - Overlays



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.

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>

It generates the following output −

Overlay
Advertisements