Retrieve geographical JSON data from the mapbox API to identify if a point falls within a polygon area

I came across a helpful tutorial that guided me on how to check if a point lies within a specific polygon displayed by a marker:

The tutorial worked smoothly by fetching the polygon geoJSON data using ajax and integrating it into the map. However, I already have my own mapbox map set up with a polygon area defined. I am utilizing their API for displaying my map and now require access to the geoJSON data in order to determine if a point falls within this specified area. How can I achieve this through the API?

Below is how I load the map, the geoJSON data, and a function to verify if a point is located within the geoJSON-defined area:

// Establishing connection with mapbox
var mapID = "<map-id>";
L.mapbox.accessToken = "<my-token>";

// Initializing the map
var map = L.mapbox.map("mapData", mapID, {
  attributionControl: false, 
  zoomControl: false
}).setView([53.799, -1.548], 13, {
  pan: { animate: true },
  zoom: { animate: true } 
});

// Retrieving geoJSON data
var geoJson;
$http.get("https://a.tiles.mapbox.com/v4/" + mapID + "/features.json?access_token=" + L.mapbox.accessToken).success(function(data){
  geoJson = data;
});

// Checking point in polygon
function determinePointInPolygon(){
  var coords = [-1.3, 5.2];
  var layer = leafletPip.pointInLayer(coords, L.geoJson(geoJson), true);
  if (!layer.length) // Point does not fall within the polygon
  else // Point lies inside the polygon
}

Answer №1

The various components are integrated into a L.mapbox.featureLayer that is accessible within your L.mapbox.Map instance. Assuming you have stored your map instance as map, your layer can be accessed using map.featureLayer:

// Ensure the featureLayer is ready
map.featureLayer.on('ready', function (e) {
    // Iterate through the features
    e.target.eachLayer(function (layer) {
        // Perform your tasks here
        // "layer" contains an instance of the marker/polygon/polyline
        // "layer.feature" holds the actual geojson feature
    });
});

For illustration purposes, here's an example: http://plnkr.co/edit/D5IfRTLV0yXTqOmzNCYA?p=preview

If desired, you could load the tiles and features separately by initializing your map without a mapid:

var map = L.mapbox.map('mapbox', null, {
    'center': [0, 0],
    'zoom': 1
});

var tileLayer = L.mapbox.tileLayer('yourMapId').addTo(map);

var featureLayer = L.mapbox.featureLayer('yourMapId').addTo(map);

Example: http://plnkr.co/edit/9pYeRu6UmxuVL1TLzwPR?p=preview

In this scenario, omit the addTo method, process your features first, then add the layer to the map:

var featureLayer = L.mapbox.featureLayer('yourMapId');
// Ensure the featureLayer is ready
featureLayer.on('ready', function (e) {
    // Iterate through the features
    e.target.eachLayer(function (layer) {
        // Perform your tasks
    });
    // Add layer to the map
    e.target.addTo(map);
});

You have options on how to proceed. However, to address your question directly (although it may no longer be relevant), the GeoJSON feature collection can be obtained using L.mapbox.FeatureLayer's getGeoJSON method (only once the layer is ready):

// Ensure the featureLayer is ready
featureLayer.on('ready', function (e) {
    // Retrieve your feature collection
    var geojson = e.target.getGeoJSON();
});

Answer №2

If you need to store the JSON data somewhere else after fetching it, you can follow these steps:

Start by creating a global object where you will save the JSON:

var fetchedJSON;

Once you have retrieved the JSON data, assign it to the global object:

$.ajax({
    url: '/mapbox.js/assets/data/us-states.geojson',
    dataType: 'json',
    success: function load(data) {
        fetchedJSON = data; // Save the retrieved data here
        var statesLayer = L.geoJson(data).addTo(map);
        L.marker([38, -102], {
            icon: L.mapbox.marker.icon({
                'marker-color': '#f86767'
            }),
            draggable: true
        }).addTo(map)
        .on('dragend', function(e) {
            var layer = leafletPip.pointInLayer(this.getLatLng(), statesLayer, true);
            if (layer.length) {
              stateInfo.innerHTML = '<strong>' + layer[0].feature.properties.name + '</strong>';
            } else {
              stateInfo.innerHTML = '';
            }
        });
    }
});

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

Configuring a Node application for a production server with Babel

I am in the process of preparing my very first node app for a production server. The build and serve scripts I am using are based on those provided by babel "scripts": { "start": "nodemon --exec babel-node server.js --ignore public/", "build": "b ...

The error message "TypeError: e.preventDefault is not a function" indicates that

I'm fairly new to JavaScript and jQuery, and I've incorporated two jQuery plugins into my code - jQuery form validator and jQuery form ajaxSubmit. Initially, everything was working fine with normal AJAX submission until I needed to post a file, w ...

Javascript Steps to trigger a function when selecting the Stay on Page option in Google Chrome

If you're testing my code in the Chrome Browser, hitting refresh will prompt you with 2 options. Leave This Page Stay on This Page By clicking on the Stay on this page button, it should trigger my custom function displayMsg(). Can anyone pr ...

Refresh the html page periodically by utilizing ajax every X seconds

Recently, I came across a post discussing the topic of automatically refreshing an HTML table every few seconds. The post can be found here. Currently, I am working with Rails and I want to achieve a similar functionality. However, I specifically want to ...

Utilize Three.js to Add Depth to 2D Images with Extrusion

After searching online, I have been unable to find a method to extrude a colored image in Three.js. My goal is to create a design similar to a Minecraft item where the image is used to generate an extruded geometry. An example of what I'm trying to ac ...

Struggling with a Failed prop type error in React? Learn how to resolve the issue of an Invalid prop being

I am currently in the process of developing a small react application where users can register, login, and perform various other actions. With respect to the Login feature, I have implemented a login form that includes error validation from the backend. Ho ...

Trouble with getElementsByClassName not targeting several divs at once

<a id="backgroundenamel_realbutton_powderblue" href="javascript:set_radio('radio_bgenamel_powderblue');" class="radio-picture-enamel" style="background-color: #97b4d2;" onclick="document.getElementsByClassName('cx00ringbuilder_topinsi ...

Controller detects $broadcast() event triggered twice from Angular $rootScope

Triggering a broadcast event on button click: $scope.onButtonClick = function(){ $rootScope.$broadcast('onButtonClick'); } And listening for the event in another controller: $rootScope.$on('onButtonClick',function(event){ alert ...

Warning: Neglecting to handle promise rejections is now considered outdated and discouraged

I encountered this issue with my code and I'm unsure how to resolve it. DeprecationWarning: Unhandled promise rejections are deprecated. In the future, unhandled promise rejections will terminate the Node.js process with a non-zero exit code. This ...

What is the best way to manage user sessions for the Logout button in Next.js, ensuring it is rendered correctly within the Navbar components?

I have successfully implemented these AuthButtons on both the server and client sides: Client 'use client'; import { Session, createClientComponentClient } from '@supabase/auth-helpers-nextjs'; import Link from 'next/link'; ...

Stop users from inputting particular words into a <textarea> box

I recently watched a tutorial on YouTube by the developphp guy and learned how to prevent people from inputting inappropriate words in my form's text area. However, I want to block multiple words instead of just one, but the tutorial didn't cove ...

Video demo: Issue with Bootstrap navigation bar expansion being truncated

When developing my React app, I installed the latest Bootstrap using npm by running: npm install bootstrap followed by: npm install bootstrap jquery and then: npm install jquery popper.js Initially, my Navbar functioned perfectly when the window was wid ...

Enhance Data3 Sankey to disperse data efficiently

There are a few instances where the D3 Sankey spread feature is showcased here. However, it seems that this specific function is not included in the official D3 Sankey plugin. Is there anyone who can assist me in obtaining the code for the Spread function ...

Is it possible to replicate two arrays in Angular through echoing?

I've run into an issue where I am struggling to return two arrays from an ajax request between Angular and PHP. Each array works fine on its own, but when trying to return both together, I encounter problems. I attempted to place the two arrays within ...

It appears that the event listener attached with the ".on()" method has suddenly ceased functioning

Starting off, here is a link to my project on jsfiddle I will discuss how it's supposed to work and the main issue I am facing. The project consists of three "lines" represented at the top by a selector box. Each line has different "parts" displayed ...

Using createContext or useContext results in an undefined value being returned

When I console.log(user), it is returning undefined instead of the expected result: [{ id: 1, name: 'username' }] . I am unsure why this is happening. If you have any insights or suggestions on how to fix this issue, please let me know. It' ...

Exploring JSON data structures using autocomplete functionalities

Here's the code I'm working with: <s:hidden id="s" value="%{Users}"/> The variable Users contains an array list of User objects. This code is written in Javascript. I want to access Users as JSON for auto-complete functionality: var valu ...

Interference of setInterval with other setInterval functions

Attempting to set up multiple setInterval functions and store them (for later clearing) results in the last setInterval overriding the previous ones. This causes each interval to execute only once, with the same output. Below is a code snippet demonstrati ...

The secondary angular button is failing to execute the function

Can someone help me with a small issue? I have two buttons on a webpage that should both contact a server. However, only the first button sends a HTTP request when clicked. <html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8 ...

What could be causing all the flickering in this presentation?

Check out the jQuery slideshow I uploaded on my blog at robertmarkbramprogrammer.blogspot.com/2010/09/jquery-slideshow.html The slideshow is flickering in Chrome but looks fine in IE, Firefox, and even the standalone version. You can view it here: Here i ...