Leaflet Draw determines whether a polygon encompasses another polygon

I have a question regarding the Leaflet Draw plugin. I am able to determine if a polygon contains markers or if a marker is placed within a polygon using the code snippet below:

polygon.getBounds().contains([latitude, longitude])

I'm interested in finding an example that can detect when a drawn polygon touches, contains, intersects with another polygon.

Is there a straightforward way to achieve this?

Thank you for your time. Best regards!

Answer №1

While it is true that Leaflet does not have built-in support to check if a polygon is contained inside another one, there are alternative methods available. GeoScript offers such methods, but they may be complex and lacking in documentation.

Personally, I prefer using JTS (or its JavaScript version JSTS) for tasks like this. Converting coordinates from Leaflet or Google Maps to JSTS format is straightforward:

function _leafletLatLng2JTS (polygon) {
        var coordinates = [];
        var length = 0;
        if (polygon && polygon.length) {
            length = polygon.length;
        }
        for (var i = 0; i < length; i++) {
            if (polygon.length) {
                coordinates.push(new jsts.geom.Coordinate(polygon[i].lat, polygon[i].lng));
            }
        }
        return coordinates;
}

You can then create two JSTS polygons and check if one is within the other with the following code:

function _isWithin (firstLayer, secondLayer) {

        var firstInput = _leafletLatLng2JTS(firstLayer.getLatLngs()[0]),
                secondInput = _leafletLatLng2JTS(secondLayer.getLatLngs()[0]),
                geometryFactory = new jsts.geom.GeometryFactory();
        
        firstInput.push(firstInput[0]);
        secondInput.push(secondInput[0]);

        var firstPolygon = geometryFactory.createPolygon(firstInput),
                secondPolygon = geometryFactory.createPolygon(secondInput);

        var isWithin = firstPolygon.contains(secondPolygon);

        return isWithin;
}

To see how this can be applied with the Leaflet.Draw plugin, visit this jsFiddle. This example allows you to draw two layers on the map (rectangles or polygons) and determine if one is contained within the other.

UPDATE 30.10.2017:

You can also utilize turf.js for similar functions, such as the booleanContains method.

Answer №2

Unfortunately, Leaflet does not offer the functionality needed for these types of calculations. One alternative solution would be to utilize a library such as GeoScript. Within the GeoScript library, the geom.Geometry class provides methods like contains, within, and intersects to perform various geometric calculations. In addition, it offers advanced functions such as covers, crosses, overlaps, and touches to meet your specific requirements.

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

modify the structure of an object according to specific conditions

So, I have this object that looks like the following. I'm currently working on restructuring the object based on the parent and child relationship. var b = []; for(var i=0;i<a.length;i++){ if(a[i].parent == null){ const children = a.filter(x => ...

Issue encountered when employing the spread operator on objects containing optional properties

To transform initial data into functional data, each with its own type, I need to address the optional names in the initial data. When converting to working data, I assign a default value of '__unknown__' for empty names. Check out this code sni ...

What is the best way to deactivate a button with an onclick function in javascript?

I would like to enhance the button click event behavior by disabling it after it has been clicked. How can I modify the function so that when the button is clicked, it becomes disabled and then redirects to the specified URL? <form id="edit" action=" ...

What is the best way to combine two arrays into a single array using AngularJS?

Here is a code snippet: $scope.studentDetails=[]; $scope.studentDetails=[0][id:101,name:one] [1][id:102,name:two] [2][id:103,name:three] $scope.studentMarks=[]; $scope.studentMarks=[0][id:101,marks:78] ...

jquery is showing up in the browserify bundle.js file, however, it is not functioning properly

Currently, I am trying to follow a brief tutorial on how to use Browserify. Despite following the instructions precisely, jQuery seems to not be working properly when bundled. Specifically, the button element in my app.js code is not appended to the body. ...

The for loop GET request is not successfully pushing data to MongoDB, leaving the database with no entries

My current challenge lies in transmitting data from my for loop to MongoDB. Upon executing the js file using node initCount.js in the console, no errors are returned and everything seems to be working correctly. However, upon checking my MongoDB backend, I ...

Include a new variable in a JavaScript email template

Is there a way to include the variable bob in the body of an email? var bob; function sendMail() { var link = "mailto:YourEmailHere" + "?cc=" + "&subject=App Build Link Buit With MWFPRO's App Build Tool" + "&body=Hi ...

What could be causing TypeScript to throw errors when attempting to utilize refs in React?

Currently, I am utilizing the ref to implement animations on scroll. const foo = () => { if (!ref.current) return; const rect = ref.current.getBoundingClientRect(); setAnimClass( rect.top >= 0 && rect.bottom <= window.i ...

JavaScript regex for the 'hh:mm tt' time format

I need to validate time in the format 'hh:mm tt'. Here is an example of what needs to be matched: 01:00 am 01:10 Pm 02:20 PM This is what I have tried so far: /^\d{2}:\d{2}:\s[a-z]$/.test('02:02 am') ...

Guide on generating a PDF on the client side and opening it in a new browser tab using AngularJS

In need of assistance with creating a PDF file on the client side using AngularJS and downloading it in a new tab on the browser. Any suggestions on how to achieve this task? ...

Positioning Images in Tailwind Modals

I'm currently working on building a modal using Tailwind in Vue, but I've run into some challenges with aligning the elements inside the modal as desired. I've experimented with removing certain Tailwind classes and have tried implementing ...

What is the process for activating JavaScript and embedding it into an HTML document?

I am currently utilizing a JavaScript API that contains several functions. How can I incorporate it into an HTML file? One of the functions, "api.ping()", performs well on PowerShell, but I am encountering difficulties with displaying it on an HTML file. ...

ProgressMeterJS Plugin - Full-width Progress Bar

I have encountered a question regarding this particular plugin found at: My goal is to adjust the progress bar's width to 100% so it matches the width of its container. So far, I have made modifications to the plugin by changing the following line: ...

Convert text into a clickable link

Creating a form with numerous text fields, some of which require numerical input. The main goal is to have users enter a tracking number, order number, or any other type of number that, when submitted, will open a new URL in a separate window with the spec ...

There is an issue showing up in the console: $(…).datepicker is not defined as a function

I am new to using HTML with JavaScript. I attempted to implement a datepicker, but unfortunately, it is not working as expected. The error message I am receiving is '$(...).datepicker is not a function' in the console. I am utilizing multiple f ...

Choosing an option in react-select causes the page to unexpectedly shift

Encountering a problem with a mobile modal developed using react-select. The selectors are within a div with fixed height and overflow-y: scroll. Upon selecting an option for the 'Choose observer' select, the entire modal briefly jumps down in th ...

Trouble encountered while using useRef in TypeScript

I'm encountering an issue with the code below; App.tsx export default function App() { const [canvasRef, canvasWidth, canvasHeight] = useCanvas(); return ( <div> <canvas ref={canvasRef} /> </div> ) ...

What is the best way to switch a Boolean value in React Native?

Struggling with toggling a Boolean state from true to false when the result is undefined. Tried several methods but none seem to work. The boolean state in the constructor is defined like this: class UserInfo extends Component{ constructor(props){ s ...

Struggling with TypeScript and JsObservable? Let us assist you!

Having previous experience with JSRender, JSViews, and JSObservables, I recently embarked on a new project using TypeScript. Unfortunately, I am struggling to understand how to properly utilize TypeScript in my project, especially when it comes to referenc ...

Tips for accomplishing multiple event triggers and event recollection (benefits that combine features of events and promises)

What I Need Seeking an event system that meets my requirements due to the asynchronous nature of my applications. Specifically, I need the events to have the ability to fire multiple times and for listeners to immediately respond if an event has already b ...