Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using it's URL and the proper URL extention.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <!DOCTYPE html>
<html lang="en" dir="ltr">
   <head>
      <meta charset="utf-8">
     
           <!-- Load Leaflet from CDN -->
      <link rel="stylesheet" href="https://unpkg.com/leaflet@1.5.1/dist/leaflet.css"
      integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ=="
      crossorigin=""/>
      <script src="https://unpkg.com/leaflet@1.5.1/dist/leaflet.js"
      integrity="sha512-GffPMF3RvMeYyc1LWMHtK8EbPv0iNZ8/oTtHPx9/cc2ILxQ+u905qIwdpULaqDkyBKgOaB57QTMg7ztg8Jm2Og=="
      crossorigin=""></script>
     
      <title></title>
   </head>
   <body>



         <div id="leafletMapid" class="mapdiv"></div>

         <div class="activeArea"></div>

         <div class="controlButtons">
            <button type="button" name="button" id="randomMarker">Create a Random Maker</button>
            <br>
            <button type="button" name="button" id="clearRandomMarkers">Clear Random markers</button>
         </div>




   </body>
</html>

              
            
!

CSS

              
                body{
   position: relative;
}

html,
body,
#leafletMapid{
  height:100%;
  width: 100%;
  margin: 0;
  padding: 0;
}

#leafletMapid{
   z-index: 0;
}

.controlButtons{
   position: absolute;
   bottom: 50px;
   right: 50px;
   z-index: 10;
}

#randomMarker,
#clearRandomMarkers{
   width: 100%;
   margin-bottom: 10px;
}

.activeArea{
   position: absolute;
   top: 5%;
   left: 10%;
   height: 50%;
   width: 50%;
   border: 2px solid black;
   pointer-events: none;
}

              
            
!

JS

              
                ///////////////////////////////////////////////
// leaflet.activearea.js code:
///////////////////////////////////////////////

(function(previousMethods){
if (typeof previousMethods === 'undefined') {
    // Defining previously that object allows you to use that plugin even if you have overridden L.map
    previousMethods = {
        getCenter: L.Map.prototype.getCenter,
        setView: L.Map.prototype.setView,
        setZoomAround: L.Map.prototype.setZoomAround,
        getBoundsZoom: L.Map.prototype.getBoundsZoom,
        scaleUpdate: L.Control.Scale.prototype._update,
        PopupAdjustPan: L.Popup.prototype._adjustPan
    };
}


L.Map.include({
    getBounds: function() {
        if (this._viewport) {
            return this.getViewportLatLngBounds()
        } else {
            var bounds = this.getPixelBounds(),
            sw = this.unproject(bounds.getBottomLeft()),
            ne = this.unproject(bounds.getTopRight());

            return new L.LatLngBounds(sw, ne);
        }
    },

    getViewport: function() {
        return this._viewport;
    },

    getViewportBounds: function() {
        var vp = this._viewport,
            topleft = L.point(vp.offsetLeft, vp.offsetTop),
            vpsize = L.point(vp.clientWidth, vp.clientHeight);

        if (vpsize.x === 0 || vpsize.y === 0) {
            //Our own viewport has no good size - so we fallback to the container size:
            vp = this.getContainer();
            if(vp){
              topleft = L.point(0, 0);
              vpsize = L.point(vp.clientWidth, vp.clientHeight);
            }

        }

        return L.bounds(topleft, topleft.add(vpsize));
    },

    getViewportLatLngBounds: function() {
        var bounds = this.getViewportBounds();
        return L.latLngBounds(this.containerPointToLatLng(bounds.min), this.containerPointToLatLng(bounds.max));
    },

    getOffset: function() {
        var mCenter = this.getSize().divideBy(2),
            vCenter = this.getViewportBounds().getCenter();

        return mCenter.subtract(vCenter);
    },

    getCenter: function () {
        var center = previousMethods.getCenter.call(this);

        if (this.getViewport()) {
            var zoom = this.getZoom(),
                point = this.project(center, zoom);
            point = point.subtract(this.getOffset());

            center = this.unproject(point, zoom);
        }

        return center;
    },

    setView: function (center, zoom, options) {
        center = L.latLng(center);
        zoom = zoom === undefined ? this._zoom : this._limitZoom(zoom);

        if (this.getViewport()) {
            var point = this.project(center, this._limitZoom(zoom));
            point = point.add(this.getOffset());
            center = this.unproject(point, this._limitZoom(zoom));
        }

        return previousMethods.setView.call(this, center, zoom, options);
    },

    setZoomAround: function (latlng, zoom, options) {
        var vp = this.getViewport();

        if (vp) {
            var scale = this.getZoomScale(zoom),
                viewHalf = this.getViewportBounds().getCenter(),
                containerPoint = latlng instanceof L.Point ? latlng : this.latLngToContainerPoint(latlng),

                centerOffset = containerPoint.subtract(viewHalf).multiplyBy(1 - 1 / scale),
                newCenter = this.containerPointToLatLng(viewHalf.add(centerOffset));

            return this.setView(newCenter, zoom, {zoom: options});
        } else {
            return previousMethods.setZoomAround.call(this, latlng, zoom, options);
        }
    },

    getBoundsZoom: function (bounds, inside, padding) { // (LatLngBounds[, Boolean, Point]) -> Number
        bounds = L.latLngBounds(bounds);

        var zoom = this.getMinZoom() - (inside ? 1 : 0),
            maxZoom = this.getMaxZoom(),
            vp = this.getViewport(),
            size = (vp) ? L.point(vp.clientWidth, vp.clientHeight) : this.getSize(),

            nw = bounds.getNorthWest(),
            se = bounds.getSouthEast(),

            zoomNotFound = true,
            boundsSize;

        padding = L.point(padding || [0, 0]);

        do {
            zoom++;
            boundsSize = this.project(se, zoom).subtract(this.project(nw, zoom)).add(padding);
            zoomNotFound = !inside ? size.contains(boundsSize) : boundsSize.x < size.x || boundsSize.y < size.y;

        } while (zoomNotFound && zoom <= maxZoom);

        if (zoomNotFound && inside) {
            return null;
        }

        return inside ? zoom : zoom - 1;
    }
});

L.Control.Scale.include({
    _update: function () {
        if (!this._map._viewport) {
            previousMethods.scaleUpdate.call(this);
        } else {
            var bounds = this._map.getBounds(),
                centerLat = bounds.getCenter().lat,
                halfWorldMeters = 6378137 * Math.PI * Math.cos(centerLat * Math.PI / 180),
                dist = halfWorldMeters * (bounds.getNorthEast().lng - bounds.getSouthWest().lng) / 180,
                options = this.options,
                maxMeters = 0;

            var size = new L.Point(
                this._map._viewport.clientWidth,
                this._map._viewport.clientHeight);

            if (size.x > 0) {
                maxMeters = dist * (options.maxWidth / size.x);
            }

            this._updateScales(options, maxMeters);
        }
    }
});

L.Map.include({
    setActiveArea: function (css) {
        if( !this._viewport ){
            //Make viewport if not already made
            var container = this.getContainer();
            this._viewport = L.DomUtil.create('div', '');
            container.insertBefore(this._viewport, container.firstChild);
        }

        if (typeof css === 'string') {
            this._viewport.className = css;
        } else {
            L.extend(this._viewport.style, css);
        }
        return this;
    }
});

L.Popup.include({
    _adjustPan: function () {
        if (!this._map._viewport) {
            previousMethods.PopupAdjustPan.call(this);
        } else {
            if (!this.options.autoPan) { return; }

            var map = this._map,
                vp = map._viewport,
                containerHeight = this._container.offsetHeight,
                containerWidth = this._containerWidth,
                vpTopleft = L.point(vp.offsetLeft, vp.offsetTop),

                layerPos = new L.Point(
                    this._containerLeft - vpTopleft.x,
                    - containerHeight - this._containerBottom - vpTopleft.y);

            if (this._animated) {
                layerPos._add(L.DomUtil.getPosition(this._container));
            }

            var containerPos = map.layerPointToContainerPoint(layerPos),
                padding = L.point(this.options.autoPanPadding),
                paddingTL = L.point(this.options.autoPanPaddingTopLeft || padding),
                paddingBR = L.point(this.options.autoPanPaddingBottomRight || padding),
                size = L.point(vp.clientWidth, vp.clientHeight),
                dx = 0,
                dy = 0;

            if (containerPos.x + containerWidth + paddingBR.x > size.x) { // right
                dx = containerPos.x + containerWidth - size.x + paddingBR.x;
            }
            if (containerPos.x - dx - paddingTL.x < 0) { // left
                dx = containerPos.x - paddingTL.x;
            }
            if (containerPos.y + containerHeight + paddingBR.y > size.y) { // bottom
                dy = containerPos.y + containerHeight - size.y + paddingBR.y;
            }
            if (containerPos.y - dy - paddingTL.y < 0) { // top
                dy = containerPos.y - paddingTL.y;
            }

            if (dx || dy) {
                map
                    .fire('autopanstart')
                    .panBy([dx, dy]);
            }
        }
    }
});
})(window.leafletActiveAreaPreviousMethods);


///////////////////////////////////////////////
// My Code
///////////////////////////////////////////////

var leafletMap = L.map('leafletMapid', {
  center: [33.270, -116.650],
  zoom: 8
});

// use only active activearea
leafletMap.setActiveArea('activeArea')

//add a baseLayer
var baseLayer =  new L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}', {
      attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
      maxZoom: 18,
      id: 'mapbox.outdoors',
      accessToken: 'pk.eyJ1Ijoic2x1dHNrZTIyIiwiYSI6ImNqeGw1Y3BibDAybG4zeHFyaXl3OXVwZXUifQ.fZ_5Raq5z-DUpo2AK-bQHA'
      });

baseLayer.addTo(leafletMap)






//-----------------------------//
//       RANDOM MARKERS
//-----------------------------//

// Make empty array to recieve randomly generated markers
randomMarkerArray = [];

// Useful random number function
function randomNumber(min, max){
   return ( Math.random() * (max - min) ) + min
};

// Define buttons
var randomMarkerButton = document.querySelector('#randomMarker');
var clearMarkersButton = document.querySelector('#clearRandomMarkers');

// Empty variable to recieve the layergroup which is created when a the button is pressed
var randomMarkerGroup;

// When the button is pressed:
randomMarkerButton.addEventListener("click", function(){
   // Get map bounds:
   let mapBoundLeft = leafletMap.getBounds()._southWest.lng;
   let mapBoundRight = leafletMap.getBounds()._northEast.lng;
   let mapBoundTop = leafletMap.getBounds()._northEast.lat;
   let mapBoundBottom = leafletMap.getBounds()._southWest.lat;

   // Make random number within bounds
   let randomLng = randomNumber(mapBoundLeft, mapBoundRight);
   let randomLat = randomNumber(mapBoundTop, mapBoundBottom);

   let position = [randomLat, randomLng];

   // Create a random marker
   let randomMarker = L.marker( position )
      .bindPopup(`This is a randomly placed marker<br>
         <br>
         Latitude: ${randomLat}<br>
         Longitude: ${randomLng}<br>`);


   // Give each random marker its own name with its index for easy reference
   randomMarker._name = `Random Marker ${randomMarkerArray.length + 1}`;
   // Push it into the array
   randomMarkerArray.push(randomMarker);

   // Create layerGroup using the array
   randomMarkerGroup = L.layerGroup( randomMarkerArray )
      .addTo(leafletMap);
   // Open popup on most recently added marker
   randomMarkerArray[randomMarkerArray.length - 1].openPopup();

})


clearMarkersButton.addEventListener("click", function(){
   // Remove the layergroup of random markers
   randomMarkerGroup.remove();
   // Empty the array to truly refresh the random marker layer
   randomMarkerArray = [];
}, false);

              
            
!
999px

Console