Issues with Leaflet's MaxBounds functionality - boundary constraints not functioning as expected

I recently experimented with Leafletjs maxBounds by testing it out using code from Mapbox's example.

For my complete code, you can also view it on this jsfiddle link.

<!DOCTYPE HTML>
<html>
<head>
    <title>leaflet bounds test</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, minimal-ui" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge">

        <!-- leafletjs -->
        <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>

        <style>
            body {
                margin: 0;
                padding: 0;
            }
            html, body, #map {
                height: 100%;
                width: 100%;
            }
        </style>
</head>

<body>
    <div id="map">
        <script>

            var southWest = L.latLng(40.712, -74.227),
                northEast = L.latLng(40.774, -74.125),
                mybounds = L.latLngBounds(southWest, northEast);

            var map = L.map('map').setView([40.743, -74.176], 17);
            L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png' , {
                maxBounds: mybounds,
                maxZoom: 18,
                minZoom: 16,
                attribution: '&copy; <a href="https://openstreetmap.org">OpenStreetMap</a> contributors'
            }) .addTo(map);

            L.marker([40.743, -74.176]) .addTo(map);

        </script>
    </div>        
</body>

The result on jsfiddle seems to be displayed oddly, and I am unsure why that is happening.

Can anyone explain why the code above does not behave like the one in the Mapbox example?

Answer №1

This is the final version of my code.

const mapSettings = L.map('map', {
    maxZoom: 18,
    minZoom: 16,
    maxBounds: [
        //south west
        [40.712, -74.227],
        //north east
        [40.774, -74.125]
        ], 
}).setView([40.743, -74.176], 17);

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

L.marker([40.743, -74.176]) .addTo(mapSettings);

Answer №2

Remember to specify bounds when using L.tileLayer, not maxBounds.

Check out the bounds reference here.

You may have loaded the wrong leaflet.css file in JSFiddle. Make sure to use this correct source:

It's best practice to avoid percent sizes in JSFiddle and opt for pixel sizes instead. Here's a functional JSFiddle link: http://jsfiddle.net/1zyL4q4a/4/

 L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png' , {
            bounds: mybounds,
            maxZoom: 18,
            minZoom: 16,
            attribution: '&copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors'
  }).addTo(map);

Answer №3

It appears that in the initial example you have provided, the map being used is not from Leaflet but rather from Mapbox. This can be determined by examining the HTML script links at the top of your code. Additionally, there seems to be some unexpected behavior when using the code from the first example with my Leaflet map.

The correct approach involves utilizing the Leaflet API, as demonstrated below:

L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png' , { bounds: mybounds, maxZoom: 18, minZoom: 16, attribution: '© OpenStreetMap contributors' }).addTo(map);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble parsing multiple JSON rows in JavaScript

I tried using the twitterapi to fetch my friends list in php and encoded the result as a json array. However, I'm facing difficulty parsing the json array in javascript. I have confirmed that the json array generated by the php code is valid. Below is ...

Laravel triggers a 'required' error message when all fields have been filled

As I attempt to submit a form using an axios post request in laravel, I encounter an issue with the validation of the name and age fields, along with an image file upload. Here is a breakdown of the form structure: Below is the form setup: <form actio ...

Can you explain the purpose and functionality of the 'next' parameter within a middleware function in the Node.js Express framework?

Currently, I am working on Nodejs with the use of "Express js". My focus is on the implementation of "middleware functions," and here is a snippet of my existing code: const express = require('express') const app = express() ...

List within a list that is only displayed if a specific condition is

Looking for help with CSS styling to make an embedded list display as a contiguous list in the final output. Here's the scenario: <ol> <li>Coffee <! -- embedded unordered or ordered list - begin --> <ul> <li>Ap ...

Exploring the method to retrieve key value pairs within an array object using JavaScript

I have an array of JSON objects and I am trying to extract it as key-value pairs. Here is the code snippet: var fs = require('fs'); var parameters = { 'Tenantid': 'a62b57-a249-4778-9732', "packagecategoryn ...

Console output shows that the function results in undefined

When I pass a string parameter to a function, I expect the console to display "reff", but it is showing "undefined" instead. Here is the code snippet: var _ref; function foo(_ref='reff') { var bar = _ref.bar; return console.log(bar); } foo ...

Conceal Content from Onsite Search

Is it possible to conceal text from on-page browser searches (e.g. Ctrl+F) in a dependable manner while keeping it visible? I thought that adding aria-hidden="true" would address the issue, but the text remains searchable by browsers. ...

Guide to deploying a Next JS App with Mongoose for MongoDB connectivity on Vercel

I am experiencing issues when trying to deploy my Next.js app on Vercel with a MongoDB connection. I have added environment variables on the Vercel site where we deploy the Next.js app. Is there anything wrong in the following file? next.config.js module. ...

A detailed guide on sending Joomla form information to a controller function using Ajax communication

Within my Joomla 3.3 form, I have integrated an ajax script aimed at dynamically updating some form fields. The core of the script looks like this: formdata = new FormData(); jQuery.ajax({ type: "POST", dataType: "json", timeout: 6000, url: "index.php?opt ...

The jQuery Remove function that went haywire

Currently, I am delving into the world of Javascript/jQuery and attempting to construct a list of items in a table based on user input. The concept is simple - a user types text into a form, the JavaScript/jQuery captures that input and showcases it as a ...

Unable to wrap text with CSS in Internet Explorer

I am encountering some issues with certain styles that are functioning correctly in Chrome and Firefox but not in IE. The main problem I am facing is that a specific style that works fine in Chrome does not wrap text into the column in IE. To reproduce t ...

Unable to dynamically insert values into a JSON object

My goal is to populate a JSON object with objects that look like this: var books = [{ "no" : 1, "bookType":"fiction", "bookPrice": 60 },{ "no" : 2, "bookType":"f ...

Move the items downwards to occupy any empty space vertically

Just a quick overview of the code I'm working with (I am using Material UI in React). This container is meant to hold chat messages exclusively. const ChatContainer = ({ chatMessages }) => { const classes = useStyles(); return ( <Paper ...

What is the best method to dynamically assign a class to a TD element in a data table when adding

I am looking to apply a class to the td element when receiving data from an ajax call Here is the default HTML code snippet <tr> <td>@fisrt.System_Code.Code</td> <td>@fisrt.System_Code. ...

Sort an array of strings with binary search and insert a new string

My current challenge involves working with an alphabetically sorted array of strings: let collection = ["ABC", "BCD", "CAB", "FGH", "JKL", "ZKL"]; The task at hand is to insert the string "CQW" into the collection while maintaining the sorted order witho ...

Error encountered while attempting to load the vue-sanitize plugin within a Vue.JS application

Hi everyone, I'm encountering a problem with a plugin in Vue that I'm hoping to get some help with. Specifically, I am trying to incorporate vue-sanitize (available here: https://www.npmjs.com/package/vue-sanitize) into my project, but I keep re ...

Creating constant strings dynamically in JavaScript and TypeScript

I am facing a challenge with my Typescript code where I have a Constants class with multiple server URLs defined. In my Processor class, I need to create objects for each server URL and push them into an array for further processing. export class Constants ...

Showing information from a database query

Let's say we have a form that submits data to the dataprocess.php file after submission. The dataprocess.php file processes the form variables and outputs the desired results. It can be challenging to directly echo content into a specific div on a pa ...

Tips for applying stroke and shadow effects specifically when the mouse is moving over a canvas:

How can we create a shadow and stroke effect for circles drawn using HTML canvas only during mouse hover? I have two circles and would like to add a shadow and stroke effect when the mouse hovers over them. However, the issue is that once the mouse moves ...

Attempting to apply a minimum width to a th element using the min-width property

I'm trying to set a width for the second th element in this table, but it's not working as expected. <th style="min-width: 50px"> Date from </th> Can anyone provide assistance with this issu ...