Grouping geoJSON data on Mapbox / Leaflet

I am currently in the process of setting up a clustered map on mapbox, similar to the example shown here:

At the moment, my point data is being extracted from MYSQL and then converted into GeoJson using GeoPHP. You can view the current map setup here.

I was wondering if there is a way for me to integrate the MarkerCluster plugin with my GeoJson file, which is named mysql_points_geojson.php in the code snippet below:

// Bike Racks
var bikeRacksIcon = L.icon({
    iconUrl: 'bicycleparking.png',
    iconSize: [24, 28],
    iconAnchor: [12, 28],
    popupAnchor: [0, -25]
});
bikeRacks = new L.geoJson(null, {
    pointToLayer: function (feature, latlng) {
      return L.marker(latlng, {
        icon: bikeRacksIcon,
        title: feature.properties.city
      });
    },
    onEachFeature: function (feature, layer) {
      if (feature.properties) {
        var content = '<table border="0" style="border-collapse:collapse;" cellpadding="2">' +
            '<tr>' + '<th>City</th>' + '<td>' + feature.properties.city + '</td>' + '</tr>' +
            '<tr>' + '<th>Country</th>' + '<td>' + feature.properties.country + '</td>' + '</tr>' +

            '<table>';
        layer.bindPopup(content);
      }
    }
});
$.getJSON("mysql_points_geojson.php", function (data) {
    bikeRacks.addData(data);
}).complete(function () {
    map.fitBounds(bikeRacks.getBounds());
});

Answer №1

Your bike rack layer can be either a custom L.MarkerClusterGroup or a L.geoJson layer. One approach is to develop your own geojson layer that supports clustering.

Instead of using the L.geoJson layer, consider parsing the data structure from "mysql_points_geojson.php" on your own (inspired by examples at https://github.com/Leaflet/Leaflet/blob/master/src/layer/GeoJSON.js)

Alternatively, for simplicity, you could ask the server to return a straightforward array of points rather than geojson format.

In my opinion, the code should resemble this:

var bikeRacks = new L.MarkerClusterGroup({});

$.getJSON("mysql_points_geojson.php", function (data) {
    // loop through data to identify points
    // create a marker for each point
    bikeRacks.addLayer(marker);
}).complete(function () {
    map.fitBounds(bikeRacks.getBounds());
});

Answer №2

Although this may be an older post, I wanted to share my method for achieving this. I utilized the clusterMarker plugin.

    var loadData = $.getJSON("yourData.json");
     /* Set up your clusters in this section */

    var markersCluster = L.markerClusterGroup({
        spiderfyOnMaxZoom: false, 
        showCoverageOnHover: false, 
        zoomToBoundsOnClick: true 
    });
   loadData.then(function(data) {

Within this function, you can add your markers to the clusters through click events or other means.

myLocation.addTo(markersCluster);

Lastly, at the conclusion, you can add the clusters to the map.

markersCluster.addTo(myMap);

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

Navigating through various JSON arrays using Angular

I am currently working with a large JSON file in Angular and trying to iterate through it. The structure of the JSON file is as follows: { "subject1":[ { "title":"titlehere", "info":"infohere." }], ...

Issue with Datepicker in Angular Bootstrap: format identifier not being utilized

Check out this Plunk for reference. This is how my controller is set up: app.controller("myController", [ "$scope", function($scope){ $scope.DateFormat = "DD/MM/YYYY"; $scope.From = '15/01/2015'; // DD/MM/YYYY ...

How to create a model for an array object in Flutter

I am attempting to create a model array for my design table that resembles this structure. However, I am unsure of how to proceed with it. While referencing this link for my JSON array below, I encountered an error stating The json provider has syntax err ...

Showcasing articles in an XML feed according to specific keywords found in the headline

I'm currently working on designing a website for a client and I want to minimize my involvement in its maintenance. I am considering using RSS feeds to automate the process by having content posted on Blogger and then feeding it to the site. However, ...

Why isn't pagination typically positioned inside of a tbody element rather than before or after it?

I've created a user table that is based on the number parameter. I added a filter that listens to input and performs an AJAX call each time with the filter applied to the name field. However, the pagination is initially displayed ABOVE the entire ta ...

Guide on effectively sending a secondary parameter in an ajax request

Struggling to implement a year/make/model multi-select feature, I have managed to get the scripts working. However, what appears to be missing is the ability to pass both a year and make variable together in order to fetch the final model results. Below a ...

Incorporate dynamic rules into a CSS stylesheet

I am trying to dynamically add a rule to my CSS for each element. Each rule should have a different background-image and name. However, I seem to be encountering an issue where the dynamically added div is not linking to the dynamically added CSS rule. I&a ...

What steps should be taken to validate a condition prior to launching a NextJS application?

In my NextJS project (version 13.2.4), I usually start the app by running: npm run dev But there's a new requirement where I need to check for a specific condition before starting the app. If this condition is not met, the app should exit. The condi ...

How can I interact with a v-dialog component within a child component in Vue.js using Vuetify?

Exploring Vue.js for the first time and hoping to display a login dialog upon button click. To maintain cleanliness in my code, I shifted the dialog to a child component within a parent component with nested LoginDialog. Below are snippets of the parent co ...

Employing an object from a distinct module

After creating a function to parse objects and provide getters, I encountered an issue. I need to access this object from a different module without re-parsing it each time. Is there a way to achieve this without using a global variable? var ymlParser = r ...

Has Apache initiated a forced logout process?

Running a LAMP server, I have implemented Apache basic authentication to log in users accessing the server homepage. I am currently seeking a way to enforce user logout, but my attempts with mod_session & mod_auth_form have not been successful. The page ...

How can I iterate through JSON data and showcase it on an HTML page?

I am in the process of developing a weather application using The Weather API. So far, I have successfully retrieved the necessary data from the JSON and presented it in HTML format. My next goal is to extract hourly weather information from the JSON and ...

Include criteria in my ajax call (conditional statements)

Is there a way to add conditions to my ajax request? Whenever I include the code below, it only seems to work for one item at a time. $.ajax({ type: 'GET', url: urlPost, success: function (data) { $.each(data, function (key, value) { ...

Combining an Editor and Dropdown Feature for a Single Attribute in Asp.Net MVC

How can I implement both an Editor and a Dropdown list for a single field? In the scenario where an agency is not already in the database, the user should be able to enter the agency name. Otherwise, the value should be selected from a dropdown list. I n ...

When I avoid using a string ref, I encounter the error message "Error: Function components are not allowed to have string refs"

Recently, I created a new component const Projects = () => { const state ={ activeItemID: 1 } const CarouselRef = useRef(null); const NextSlide = () => { CarouselRef.current.style = "opacity: 0"; } return( <Co ...

Determine if a div contains an svg element with JavaScript

My question involves a div containing a question mark and some SVG elements. Here is the initial setup: <div id="mydiv">?</div> When validating a form submission in my code, I check if the div text contains a question mark like this: const f ...

The Express.js server encounters a 404 error, causing it to panic and throw an exception before I can even address the issue

(Just so you know, I'm utilizing the Blizzard.js npm package in combination with Express.) I am currently working on a web application that allows users to search for statistics of specific video game characters (profiles created by players). Given t ...

Exploring the functionality of the onblur HTML attribute in conjunction with JavaScript's ability to trigger a

How do the HTML attribute onblur and jQuery event .trigger("blur") interact? Will both events be executed, with JavaScript this.trigger("blur") triggering first before the HTML attribute onblur, or will only one event fire? I am using ...

How come I am unable to save an array of objects in a State within React JS?

React JS component: When I make a request to the backend to fetch data stored in a MySQL table, it returns an array of objects. I store this data in a state called `favcoin`. However, when I console.log(favcoin), it displays an empty array [ ]. Strangely, ...

Dots are used to indicate overflow of title in React Material UI CardHeader

Is there a way to add ellipsis dots to the title in my Cardheader when it exceeds the parent's width (Card width)? Here is what I have attempted so far: card: { width: 275, display: "flex" }, overflowWithDots: { textOverflow: &apo ...