Display markers for polygons imported from a GeoJSON file on a Leaflet map

I am using a Leaflet JS map to showcase data from a GeoJSON file. However, I am facing an issue where some of the features in the GeoJSON file are polygons while others are points. My goal is to convert each polygon into a point (whether it be at the centroid, average bbox location, or any other position - precision is not crucial) so that I can transform the entire GeoJSON file into a set of points. This way, I can simplify the visualization by displaying just one Leaflet marker for each converted point, or former polygon. Additionally, I do not want to show the outlines of the original polygons.

Answer №1

If you are working with the onEachFeature option of the L.GeoJSON layer, you have the ability to run a function for each feature in your feature collection. Within this function, you can distinguish between points and polygons. Here's a brief example:

const map = L.map('map', {
    center: [0, 0],
    zoom: 0
});

const geoJsonLayer = L.geoJson(featureCollection, {
    onEachFeature: function (feature, layer) {
        // Check if feature is a polygon
        if (feature.geometry.type === 'Polygon') {
            // Customize style for polygons
            layer.setStyle({
                'weight': 0,
                'fillOpacity': 0
            });
            // Obtain bounds of polygon
            const bounds = layer.getBounds();
            // Find center of bounds
            const center = bounds.getCenter();
            // Use center to place marker on map
            const marker = L.marker(center).addTo(map);
        }
    }
}).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

Tips for activating a dropdown menu upon the selection of another menu item

I'm currently customizing my own child theme within the Genesis Framework. In my theme, when you click on a top level menu item, the sub-menu slides open horizontally beneath the menu. The issue I am facing is that to close the sub-menu, you have to c ...

Is it feasible to invoke a function in an iframe of the parent webpage using an extension?

Is it possible to trigger a function in an iframe of a parent webpage from an extension? I have set all-frames:true in manifest.json The code in iframe.html is as follows: <body> <div class="row"> <butto ...

The absence of a Bootstrap modal triggering upon page load is causing an issue

After implementing a login/signup modal on my website, I discovered that it works well, but I want it to open automatically when the page loads. I found the initial code for the modal here. I made changes to the code to try and open the reset password mod ...

Utilizing a Stripe webhook as an intermediary layer

When a user successfully checks out through my Nodejs/Express API with Stripe, I need to send them some success responses and trigger certain functions. I attempted to use the checkout.session.completed event in the webhook to determine if the checkout pr ...

Is the custom comparator in AngularJS filter not functioning properly with null values?

[New Version] I've discovered a solution to address this issue - by utilizing AngularJs version 1.3.6 or higher, items with null properties will not vanish after applying a filter and then removing it! original query below Hello everyone, I am curre ...

Troubleshooting problems with manipulating arrays within JSON using the map function

I'm currently working on a project to create a Pokemon wiki-style webpage as a beginner project. I'm trying to display the types of each Pokemon using the JSON object retrieved via axios. However, I'm encountering issues with using the map m ...

Incorporate a JavaScript script into an Angular 9 application

I have been experiencing issues trying to add a script.js file to angular.json and use it in one component. Adding a script tag directly to my HTML file is not the ideal solution. Can someone suggest an alternative approach or point out what I may be missi ...

Using Jquery in conjunction with Bootstrap 4

Whenever I execute this code while utilizing bootstrap, an error message pops up: practice.js:11 Uncaught TypeError: $(...).fadeOut is not a function This is the code that triggered the error: HTML : <!DOCTYPE html> <html> <head> ...

Create a JSON structure with nested elements

I've been attempting to create a nested JSON from a simple JSON but haven't been successful yet. Here is the JSON structure I'm trying to convert: [ { "station_id": "ESP0001", "datetime": "2022-1 ...

Sending an email through Node.js with SendGrid is not a challenge

I've got this Mailer.js file const sendgrid = require('sendgrid'); const helper = sendgrid.mail; const keys = require('../config/keys'); class Mailer extends helper.Mail { constructor({ subject, recipients ...

I have successfully implemented ngCordova local notifications, but now I am looking for a way to make it trigger for each individual

Is there a way to trigger a notification on every logged-in user's mobile device when a value is changed and saved in Firebase? Currently, I am able to send a local notification using ngCordova when a user enters text in an ionicPopup with textarea. H ...

Minimize the memory footprint of this Pandas script when loading a JSON file and saving it as a pickle

I'm having trouble trying to further optimize memory usage for my program. Essentially, I am parsing JSON log files into a pandas dataframe but encountering the following challenges: The append function is causing substantial memory consumption as i ...

Is your Javascript failing to update window.location.search?

Looking to update the URL search parameters when a user enters them in the search panel on a page. Currently attempting: $( document ).ready(function() { if ($('.o_website_license_search_panel').length) { $('.o_website_license_s ...

Accessing the information within a link or script tag by utilizing the src/href attribute

Is there a way to access the contents of a file with the following code? <link href='path/to/file'/> I know that adding the attribute type="text/css" allows for reading using document.styleSheets, but I'm struggling to retrieve the c ...

Customizing MUI DataGrid: Implementing unique event listeners like `rowDragStart` or `rowDragOver`

Looking to enhance MUI DataGrid's functionality by adding custom event listeners like rowDragStart or rowDragOver? Unfortunately, DataGrid doesn't have predefined props for these specific events. To learn more, check out the official documentati ...

`Testing the functionality of javascript/jQuery events using Jasmine`

I came across this code snippet: $(document).on('click', '#clear-button', clearCalculatedPrice) clearCalculatedPrice = -> $('#price_rule').removeAttr('data-original-title') $('#calculated-price&apos ...

Unusual behavior observed when React updates state

I am currently facing an issue where I am trying to update the state of my components through a child component, but for some reason the callback function is not registering the updated state. Method (loadModuleContent) export default class LayoutPag ...

Changing the theme of a toggle button in Jquery Mobile when the button is pressed

I have a group of buttons with a specific class <div class="prog-day"> <div class="prog-clear" data-role="controlgroup" data-type="horizontal> <a href="#" data-role="button" data-mini="true" data-theme="b">Clear</a> ...

Unlocking the power of promises: How Node.js excels at handling

I'm facing a situation where my controller code is structured like this. const Users = require("../models/users"); class UserController() { getUserById(req, res) { const id = req.params.id; const users = new Users(); ...

Using JSON to transfer information between PHP and Android devices

Currently, I am working on an android application that utilizes PHP and mysql as an external database. In my activity page, the JSON data is present but not bound in a listview. Despite numerous attempts and Google searches, I have been unable to resolve t ...