Creating a customized plugin in JavaScript that utilizes a local JSON/GeoJSON file

I am relatively new to Drupal and currently working on developing a custom map module. While my module functions correctly and displays the map along with relevant information, I encountered a challenge regarding calling my geojson file using a hard-coded path. I couldn't find documentation on how to dynamically call the file with a relative path to facilitate easy deployment of my module on different websites.

I suspect that utilizing routes might be the solution, but I'm unsure how to implement this approach effectively.

Below is a snippet of my code:

var url =  "/drupal-site/recommended-project/web/modules/custom/carto_conseillers/src/geojson/annuaire_cf.geojson";

var centerProj = new ol.proj.transform([1.33333,47.583328], 'EPSG:4326', 'EPSG:3857');

const source = new ol.source.Vector({
    url: url,
    format: new ol.format.GeoJSON(),
});

const view = new ol.View({
                       center: centerProj,
                       zoom: 8
});

const vectorLayer = new ol.layer.Vector({
  source: source,
  style: function (feature) {
    const color = feature.get('color') || '#c7c7c7';
    style.getFill().setColor(color);
    return style;
  },
});

In addition, here are snippets from my librairies.yml, routing.yml, and ModuleController.php.

Any guidance or suggestions would be greatly appreciated.

Thank you for taking the time to review this.

Best Regards

Answer №1

I recently discovered a solution by following the instructions provided here: Implementing customizable JavaScript

To implement this, simply add the following line in the controller:

  $block['#attached']['drupalSettings']['myVar'] = 'myPath';

Then, you can access the value in your JavaScript using:

var url = drupalSettings.myVar;

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

Using Ajax to insert data into WordPress

Looking to incorporate data into the WordPress database using Ajax integration. functions.php function addDataToDB(){ global $wpdb, $count; $count = 25; $wpdb->insert( 'custom_table', array( 'slid ...

Received a Vue prop as a variable name, rather than the actual string value it represents

In the parent component, my string variable is being passed down. The constant GET_STARTED is equal to the string "Get Started" <script setup> import { GET_STARTED } from '../../constants' import GreenBtn from '@/components/p ...

Bootstrap tab content getting shifted downwards

Having an issue with the Tab plugin in Bootstrap on a particular page. The tab body is being pushed down 400px below the actual tabs. This behavior is only occurring on this specific page, while most other pages using the same plugin are functioning fine. ...

Anchor no longer follows endpoint after Anchor ID is modified following creation - JSPlumb

I am currently developing an editor that involves placing shapes on a canvas and assigning IDs to them. When a shape is placed, endpoints are automatically created and attached to the shape using its ID as an anchor. //Function responsible for adding en ...

utilizing window.location.href to direct to a page with javascript capabilities

I am currently developing my own personal website. It is designed to be very light in terms of loading and content. This website relies heavily on the use of jquery, so if a user's browser does not have JavaScript enabled, the site will not function ...

AngularJS: Solving the issue of controllers not exchanging data by utilizing a service

I am working with the following controllers and service: angular.module('myApp', []); angular.module('myApp').factory('ShareService', function() { var information = {}; information.data = ""; information.setD ...

A specific image is loading after being clicked in a new page

Despite my efforts to search on various platforms, I have not been able to find a comprehensive solution to my query. Scenario: I currently have a webpage containing a div with multiple images. These images load without any issues and are set to open in ...

Creating a dynamic nested form in AngularJS by binding data to a model

Creating a nested form from a JSON object called formObject, I bind the values within the object itself. By recursively parsing the values, I extract the actual data, referred to as dataObject, upon submission. To view the dataObject in a linear format, r ...

What could be causing the issue with the variable appearing as undefined in

My class has a property: public requestLoadPersonal: Personal[] = []; As well as a method: private filterByGender(selectedValue: any): void { console.log(this.requestLoadPersonal); this.requestLoadPersonal = this.requestLoadPersonal.filter( ...

Contrasting the utilization of Angular $scope dependency with independent usage

As I delve into Angular, there's something that puzzles me. Being a newcomer to Angular, I recall a tutorial where they employed this syntax for applying properties to a controller's scope: app.controller('someCtrl', function(){ ...

3D Animation for All Browsers

I'm currently working on creating a small browser-based game and I've been experimenting with animations to get the desired effect. So far, the animation works well in Opera and Edge, although there is a slight cropping issue in Edge. Unfortunat ...

How can a personalized greeting be added in Node.js to welcome a user by their first name retrieved from a MongoDB database upon logging in?

I am looking to create a login and signup form using React that will allow users to input their name, email, and password. After submission, I want the next page to be a personalized congratulations page with the user's name dynamically inserted. Can ...

The login button has dual functionality, redirecting users to different pages based on their login status. First-time logins will be directed to an agreement page, while returning users will be

During my testing of login functionality, I follow these steps: Enter username Enter password Click on the login button Verify if the agreement page is displayed This is how my Page Object Model (POM) for the login page looks like: class loginPage { ...

What is the optimal order for executing JavaScript, jQuery, CSS, and other controls to render an HTML page efficiently?

What are some recommended strategies for optimizing webpage loading speed? What key factors should be taken into consideration? ...

Create an Array of Objects by Sharing Your Post

Can someone guide me on the correct way to post my data here? I have been encountering errors while trying to insert data into user.SavedMachines.Id and user.SavedMachines.Date. I attempted using user.SavedMachines.Id = req.body.SavedMachinesId and user. ...

Challenge with JavaScript personalized library

No matter how many times I review my code, I find myself perplexed. Despite my efforts to create a custom library of functions from scratch (shoutout to stackoverflow for guiding me on that), the results are leaving me puzzled. A javascript file is suppose ...

The useMutation function trapped in an endless loop

I've been encountering an issue while running a query to save an entity in the database using usemutation. The saveVisa() mutation seems to be stuck in an infinite loop, creating the same element multiple times without any clear reason. import {React, ...

The ID Token could not be verified due to an invalid jwt.split function

I'm currently working on validating a Google ID Token on my Node.js server. Unfortunately, I've encountered the following error: The ID Token cannot be verified: jwt.split is not a function For reference, here is the link to the code that I am ...

Puppeteer with Typescript: Encountering issues during the transpilation process

The issue stems from the fact that I am unable to use Javascript directly due to Firebase Functions Node.JS version lacking support for Async/Await. As a workaround, I have converted the code into Typescript and am currently attempting to transpile it to c ...

Make the element switch from hidden to visible when hovering over it using CSS

I had a challenge to only show some rating text on my website when I hovered over it. Being new to coding with CSS and JavaScript, I was experimenting with overriding styles using the Stylebot extension in Chrome. I encountered an issue while trying to mo ...