Mapbox Heatmap with gl js API, how to change background or overlay color to be less dark?

I am using this tutorial to make a heatmap.

Mapbox Heatmap Tutorial

I have barely changed the display settings from how it is displayed here.

I am hoping to make the overlay less dark so that smaller towns and street names show up more clearly. Or possibly even do a heatmap over the satelite or streetview.

More simply how do I style the overlay or background to be a different color or lighter?

And if I wanted to how would I do a heatmap over a satellite or streetview layer?

Making Leaflet.FeatureGroup.SubGroup work so that user can upload CSV file and markers display

I created a code that use a csv file that is imported into the project folder so that it can display the markers for each data point, while making marker clusters and layers. My code works great, but my boss would like me to add a function so that he could add a csv file himself on the interface. I figured out another code so that he can add a csv file and display the markers, but I don’t know how to apply it to the code I already have so that the layers and marker subgroups still work. Can someone please help me? I’m an engineering intern with some coding experience but not enough to really know what I’m doing on this project and would really appreciate any and all help. Thank you.

Here’s my original code that works great and I want to keep, just with the added CSV file uploaded feature:

    <!DOCTYPE html>
<html>

<head>
  <title>leaflet-map-csv</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta charset="utf-8">

  <link rel="stylesheet" type="text/css" href="style.css">

  <link rel="stylesheet" href="https://unpkg.com/leaflet-control-geocoder/dist/Control.Geocoder.css" />

  <link rel="stylesheet" href="https://unpkg.com/leaflet.markercluster/dist/MarkerCluster.css" />
  <link rel="stylesheet" href="https://unpkg.com/leaflet.markercluster/dist/MarkerCluster.Default.css" />

  <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" />

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/0.4.2/leaflet.draw.css" />

  <style>
    body {
      margin: 0;
      padding: 0;
    }

    #map {
      position: absolute;
      top: 0;
      bottom: 0;
      right: 0;
      left: 0;
    }
  </style>

</head>

<body>
  <div id="map"></div>


  <!-- PLUG INS-->
  <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

  <script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>

  <script src="https://unpkg.com/leaflet.markercluster/dist/leaflet.markercluster.js"></script>
  <script src="https://unpkg.com/leaflet.featuregroup.subgroup/dist/leaflet.featuregroup.subgroup-src.js"></script>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/5.3.0/papaparse.min.js"></script>
  <script src="https://unpkg.com/leaflet-control-geocoder/dist/Control.Geocoder.js"></script>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/0.4.2/leaflet.draw.js"></script>

  <script>


    var map = L.map('map', {
      center: [34.098907, -118.327759], // where the map zooms in to
      zoom: 9 // can zoom from 0-18
    });


    //these are the map layers. this can be changed from choosing tiles from a website like: https://leaflet-extras.github.io/leaflet-providers/preview/
    var light = L.tileLayer('https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png', {
      attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>, &copy; <a href="https://carto.com/attribution">CARTO</a>'
    }).addTo(map);

    var terrain = L.tileLayer('https://stamen-tiles.a.ssl.fastly.net/terrain/{z}/{x}/{y}.png', {
      attribution: 'Map tiles by <a href="http://stamen.com">Stamen Design</a>, under <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a>. Data by <a href="http://openstreetmap.org">OpenStreetMap</a>, under <a href="http://www.openstreetmap.org/copyright">ODbL</a>.'
    });

    var googleSat = L.tileLayer('http://{s}.google.com/vt/lyrs=s&x={x}&y={y}&z={z}', {
      maxZoom: 20,
      subdomains: ['mt0', 'mt1', 'mt2', 'mt3']
    });


    //this just create sthe link from the layer titles to the variable
    var baseLayers = {
      "Carto Light Basemap": light,
      "Stamen Terrain Basemap": terrain,
      "Satellite Basemap": googleSat
    };


    //THIS IS THE SEARCH FUNCTION
    var geocoder = L.Control.geocoder()
      .on('markgeocode', function (event) {
        var center = event.geocode.center;
        L.marker(center).addTo(map);
        map.setView(center, 13);
        //L.circle(center, 900).addTo(map);  this creates a radius everytime you search
      })
      .addTo(map);



    //this creates the toolbar to be able to draw on the map
    var drawnFeatures = new L.FeatureGroup();
    map.addLayer(drawnFeatures);

    var drawControl = new L.Control.Draw({
      edit:
      {
        featureGroup: drawnFeatures,
        remove: true
      },
      draw: {
        polygon:
        {
          shapeOptions:
          {
            color: 'red'
          }
        },
        polyline:
        {
          shapeOptions:
          {
            color: 'green'
          }
        },
        rect:
        {
          shapeOptions:
          {
            color: 'purple'
          }
        },
        circle:
        {
          shapeOptions:
          {
            color: 'blue'
          }
        },
        marker: false // follow this format if you don't want a certain shape
      }
    });

    map.addControl(drawControl);


    //this allows the drawings to be created, saved, and edited 
    map.on("draw:created", function (e) {
      var type = e.layerType;
      var layer = e.layer;
      drawnFeatures.addLayer(layer);
    });

    map.on("draw:edited", function (e) {
      var layers = e.layers;
      layers.eachLayer(function (layer) {
      });
    });
    var controlLayers = L.control.layers(baseLayers);

    var engineerLayers = {}; // Create an object to hold the engineer marker cluster groups



    
    //this retrieves the file
    $.get('practice.csv', function (csvString) {
      var data = Papa.parse(csvString, {
        header: true,
        dynamicTyping: true
      }).data;
      var parentGroup = L.markerClusterGroup();

      for (var i in data) {
        var row = data[i];
        var engineer = row.Engineer;

        if (!(engineer in engineerLayers)) {
          // Each overlay that should actually be a part of MCG
          // should be made as a Subgroup, with the MCG as their parent
          engineerLayers[engineer] = L.featureGroup.subGroup(parentGroup, []);

          controlLayers.addOverlay(engineerLayers[engineer], engineer);
        }

        var marker = L.circleMarker([row.Latitude, row.Longitude], {
          radius: 10,
          stroke: true,
          color: getColor(engineer),
          opacity: 1,
          weight: 1,
          fill: true,
          fillColor: getColor(engineer),
          fillOpacity: 0.5
        }).bindPopup('Plan File: ' + row.PFN + '</br>' + 'Engineer: ' + row.Engineer + '</br>' + ' Date Received: ' + row.Date_Received + '</br>' + 'Status: ' + row.Status);

        // Add the marker only to its overlay
        marker.addTo(engineerLayers[engineer]);
      }

      map.addLayer(parentGroup);
      controlLayers.addTo(map);

    });




    // Must change these if engineers ever change
    function getColor(engineer) {
      switch (engineer) {
        case 'Mike':
          return 'green';
        case 'Salar':
          return 'blue';
        case 'Diego':
          return 'purple';
        case 'Saul':
          return 'orange';
        case 'Chan':
          return 'red';
        default:
          return 'black';
      }
    }

//****IF YOU ARE GETTING AN UNDEFINED LAYER, MAKE SURE TO GET RID OF ANY EXTRA SPACE IN THE CSV FILE 

  </script>
</body>

</html>

Here’s the code I have written to allow the user to upload the csv file and then to print the data

<!DOCTYPE html>
<html>
<head>
  <title>Leaflet Map with CSV Marker Data</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/leaflet.css" />
  <style>
    /* Add some styling to the map container */
    #map {
      height: 400px;
      width: 100%;
    }
  </style>
</head>
<body>
  <input type="file" id="csvFileUpload">
  <div id="map"></div>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/leaflet.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script>
    // Initialize Leaflet map
    var map = L.map('map').setView([0, 0], 2);

    // Add the tile layer (e.g., OpenStreetMap)
   var light = L.tileLayer('https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png', {
      attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>, &copy; <a href="https://carto.com/attribution">CARTO</a>'
    }).addTo(map);
    
     var baseLayers = {
      "Carto Light Basemap": light,
    };
     
     var controlLayers = L.control.layers(baseLayers);



    // Listen for file upload changes
    $('#csvFileUpload').change(function (e) {
      var file = e.target.files[0];
      var reader = new FileReader();

      // Read file contents
      reader.onload = function (e) {
        var csv = e.target.result;
        var markers = parseCSV(csv);

        // Add markers to the map
        markers.forEach(function (marker) {
          L.marker([marker.Latitude, marker.Longitude]).addTo(map)
            .bindPopup(marker.title);
        });
      };

      reader.readAsText(file);
    });

    // Parse CSV data into an array of objects
    function parseCSV(csv) {
      var lines = csv.split("n");
      var result = [];
      var headers = lines[0].split(",");

      // Iterate through each line (excluding header) and create marker objects
      for (var i = 1; i < lines.length; i++) {
        var obj = {};
        var currentLine = lines[i].split(",");

        // Populate marker object with latitude, longitude, and title
        for (var j = 0; j < headers.length; j++) {
          obj[headers[j]] = currentLine[j];
        }

        result.push(obj);
      }

      return result;
    }
  </script>
</body>
</html>

display repeat issue with for Of loop

on this expense tracker every time I submit my form the results repeat . I’m thinking it has something to do with loop or the page refresh.

function addExpense(e) {
  e.preventDefault();
  // take the values from my form 
  // add them to my local storage to avoid losing data
  let name = document.getElementById("name").value
  let selection = document.getElementById("expenseMenu").value
  let amount = document.getElementById("amount").value

  const expense = {
    name,
    selection,
    amount,
  }

  if (localStorage.getItem("ex_data") === null) {
    localStorage.setItem("ex_data", "[]")
  }
  let array = JSON.parse(localStorage.getItem("ex_data"))
  array.push(expense)
  localStorage.setItem("ex_data", JSON.stringify(array))

  document.getElementById('expForm').reset();
  display()
}

function display() {
  let display = document.getElementById("display")
  let results = JSON.parse(localStorage.getItem("ex_data"))
  for (const info of results) {
    display.innerHTML += `
            <tr>
                <td>${info.name}</td>
                <td>${info.selection}</td>
                <td>${info.amount}</td>
            </tr>`
  }
}

I’m guessing every time I submit the for of loop is iterating over the array from the beginning each time and repeating the list as a whole

Is there a way I can have two items in a flex container but only center one?

I have create the desired effect in a not-so-elegant way using absolute positioning, however this is not very good for re-usability. Is there any way I can instead put these two items in a flex container together but somehow center only the text? Also I am using an MUI icon and it appears to have an invisible square around it that pushes it out of line and am not sure how to fix that as well.

Example

Note I am using React and MUI but this seems to be more of a CSS question so it shouldn’t matter too much:

export default function CreateGuest() {
  const defaultText = 'Enter a display name'
  const [guestDisplayName, setGuestDisplayName] = useState(defaultText)
  return (
    <Box
      display="flex"
      justifyContent="center"
      margin="auto"
      sx={{
        width: 366,
        height: 386,
        backgroundColor: 'primary.contrastText',
        boxShadow: '0 2px 3px #00000053',
      }}
    >
      <Stack justifyContent="space-evenly">
        <Typography
          variant="h3"
          component="pre"
          textAlign="center"
          sx={{ position: 'relative' }}
        >
          <ChevronLeftIcon
            sx={{
              fontSize: 48,
              color: 'secondary.main',
              position: 'absolute',
              bottom: '43%',
              right: '87%',
              '&:hover': {
                cursor: 'pointer',
              },
            }}
          />
          {`Create anGuest User`}
        </Typography>
        <TextField
          label={guestDisplayName === '' ? defaultText : guestDisplayName}
          onChange={(e) => setGuestDisplayName(e.target.value)}
          variant="outlined"
          color="info"
        ></TextField>
        <Button variant="contained">Create Guest</Button>
      </Stack>
    </Box>
  )
}

Chrome keeps having Uncaught ReferenceError

Whenever I create a class in another js file, Chrome will generate Uncaught ReferenceError at random times.

In index.html:

<script src="main.js"></script>
<script src="car.js"></script>

In main.js:

const car=new Car(100,100,30,50);

In car.js:

class Car{
    constructor(x,y,width,height) {
        this.x=x;
        this.y=y;
        this.width=width;
        this.height=height;
}}

The issue would disappear after I refresh the page and a couple times and then reappear at random times.

Issue with accessing duration value of an audio file stored in variable “hh”

I’m facing an issue while trying to access the duration value of an audio file that I have stored in a variable named “hh” in Foreach Loop. The audio file itself is successfully loaded into the variable, but when I attempt to retrieve the duration using hh.duration, I’m getting “NaN” instead of the expected duration value.

Here’s a simplified version of my code:

function showcontent() {
    let songsarra = localStorage.getItem("Songs");
    let songa =JSON.parse(songsarra);
    
    document.getElementById("SongItemContainer").innerHTML = "";
    
    let x = 0;
    let index = 0;
    
    songa.forEach(()=>{
        let hh = new Audio(songa[x].filepath);        
        document.getElementById("SongItemContainer").innerHTML += `<div class="songItem">
        <img src="${songa[x].Coverpath}" alt="">
        <span class="songname">${songa[x].songName}</span>
        <span class="timestamp">${hh.duration} <i class="fa-regular fa-trash-can class="delete" onclick="deleteitem(${index})"></i> <i class="fa-regular  fa-circle-play current" id="${x}"></i></span>
        </div>`;
        x++;
        index++;
    });
}

The above code snippet results in “NaN” being printed instead of the actual duration of the audio file.

I have verified that the audio file is valid and accessible, and the loading process seems to be working correctly as I checked it in console. However, accessing the duration property returns “NaN”.

Is there something I’m missing or doing incorrectly? How can I properly retrieve the duration value of the audio file stored in the variable “hh”?

Any guidance or suggestions to help resolve this issue would be greatly appreciated. Thank you!

Did the transpiler get it wrong?

I’m using the pdf-lib package in a TypeScript project and wrote some wrapper code to use it in test automation. It worked fine. We decided to push this wrapper code to a shared project so others could use it too, but then the test breaks. After debugging, it seems that the transpiler may have caused the problem.

Pdf-lib’s PDFDict class has a get method that returns a value based on the key parameter. Internally, it is calling this.dict.get(key) where this.dict is a javascript Map object. The key parameter can be of type any.

When running from our project,
this.dict.get(key) returns FlateDecode.

When referencing the shared project,
this.dict.get(key) returns undefined.

When running from our project, the keys in this.dict and the key object passed into get are all PDFName objects.

When running from the shared project, the keys in this.dict are PDFName2 objects and the key object passed in is a PDFName3 object.

If my assumption that get is returning undefined because the Map key objects and the key passed in are 2 different types (PDFName2 vs PDFName3), did the transpiler screw up here?

el.is(“:invalid”) without jQuery

I’m thring to convert this code to vanilla JavaScript without jQuery:

if ($(el).is(":invalid")) {
  // etc
}

How do I write this code without using JavaScript?

I tried looking at youmightnotneedjquery.com , but it doesn’t seem to have this use-case.

How to check multiple variables for a change and only return those that have changed Reactjs

I am trying to create a system that checks multiple variables to their original state and only returns the ones that have changes using either javascript or react hooks

It’s for checking what changes a user made to a document in firestore
I already have all the code for timestamping when and who made the change, but right now I am just sending all the data again, even if none or very little of the data changed

Pseudocode:
`let [currentTitle, setCurrentTitle] = usestate(“title”)
let [oldText, setOldText] = usestate(“some text”)

let newTitle = “New title”
let newText = “some text”

if (New variables != Old variables) {
return the new variables that changed and the old variables`

I know that I could just do this,
if (newTitle != currentTitle) { return newTitle, currentTitle } else if ( newText != oldText ) { return newText, oldText }
but considering how messy that would be if I had dozens of variables to keep track of having to write out an else if statement for each one would make my code unreadable

I have thought about maybe pushing both into seperate arrays and comparing the two, but again I wouldn’t know how to do that with arrays. I may still look into comparing the two arrays and only returning the new item and the old item, but I feel like it may be a better solution to do what I originally thought of doing rather than that. If I am wrong on that front please let me know.

Is there a way to create a reference to a variable in JavaScript?

I need a way to pass a variable to a function and then add to that variable inside of the function. Here’s an example of what I need:

let x = 0;

function addTo(num1, num2) {
  num1 += num2;
}

addTo(x, 5); // I want this function to add 5 to x
console.log(x); // should log 5 in the console

Here’s another example of what I want to achieve in C++ code:

#include <iostream>

void addTo(int& num1, int num2) {
  num1 += num2;
}

int main() {
  int x = 0;

  addTo(x, 5);
  std::cout << x << std::endl; // outputs 5
}

Error in ./src/styles.less when upgrading from Angular 9 to 10

Im upgrading angular from 9 to 10, and when i run ng build I this error.

ERROR in ./src/styles.less (./node_modules/css-loader/dist/cjs.js??–14-1!./node_modules/postcss-loader/src??embedded!./node_mdules/less-loader/dist/cjs.js??–14-3!./src/styles.less)
Module build failed (from ./node_modules/less-loader/dist/cjs.js):

.make-grid(xs);
^
Maximum call stack size exceeded
Error in C:…node_modulesbootstraplessgrid.less (line 56, column 0)
Error:

.make-grid(xs);
^
Maximum call stack size exceeded
Error in C:…node_modulesbootstraplessgrid.less (line 56, column 0)
at C:…node_modulesless-loaderdistindex.js:62:14
@ ./src/styles.less 2:26-207
multi ./src/styles.less

Im using node 12.11.0

I think it is related to some of the imported styles inside the styles.less but with angular 9 it works fine, I don’t know what could change about those styles with angular 10.

Has anyone had a similar problem?

unable to read the data from custom Hook in react

Here I’m expecting to get the tags value from useTags Hook, But it is returning undefined. Here is my code.

App.js

export default function App() {
  const [data, setData] = useState([]);
  const [tags] = useTags();
  const clickHandler = () => {
    alert(JSON.stringify(tags));
  }
  useEffect(() => {
    setTimeout(() => { setData(["java", "javascript"]); }, 3000)
  }, []);
  console.log('[App.js] rendered');
  return (
    <div className="App">
      <TagList data={data} />
      <button onClick={clickHandler}>click</button>
    </div>
  );
}

TagList.js

import { memo, useEffect, useState } from "react";
export const useTags = (data) => {
    const [tags, setTags] = useState(data);
    const updateTags = (tags) => {
        setTags(tags);
    }
    useEffect(() => {
        setTags(data);
    }, [JSON.stringify(data)])
    return [
        tags,
        updateTags
    ]
}
const Tag = memo(({ tags, tagRemoveHandler, errIndex = -1 }) => {
    return (
        <div className="taglist-tags">
            {tags.map((tag, index) => (
                <div className={errIndex === index ? "taglist-tag error" : "taglist-tag"} key={tag} >
                    <span className="taglist-tag-text">{tag}</span>
                    <span className="taglist-tag-remove" onClick={() => tagRemoveHandler(tag)} >
                        <span className="icon-close"></span>
                    </span>
                </div>
            ))}
        </div>
    );
});
export const TagList = ({ data }) => {
    const [tags, updateTags] = useTags(data);
    const [tag, setTag] = useState("");
    const [errIndex, setErrIndex] = useState(-1);
    useEffect(() => {
        let timer;
        if (errIndex != -1) {
            timer = setTimeout(() => {
                setErrIndex(-1);
            }, 3000);
        }
        return () => {
            clearTimeout(timer);
        };
    }, [errIndex]);
    const keyDownListener = (e) => {
        if (e.key === "Enter" || e.code == "Comma") {
            e.preventDefault();
            let index = tags.indexOf(tag);
            if (index > -1) {
                return setErrIndex(index);
            }
            updateTags([...tags, tag]);
            setTag("");
        }
    };
    const changeHandler = (e) => {
        setTag(e.target.value);
    };
    const tagRemoveHandler = (t) => {
        updateTags(() => tags.filter((tag) => tag !== t));
    };
    return (
        <>
            <div style={{ marginBottom: 20 }}>
                <h2>Create tags here.</h2>
                <label>press enter to create a tag</label>
            </div>
            <div className="taglist">
                <Tag
                    tags={tags}
                    tagRemoveHandler={tagRemoveHandler}
                    errIndex={errIndex}
                />
                <textarea
                    className="taglist-input"
                    value={tag}
                    onKeyDown={keyDownListener}
                    onChange={changeHandler}
                />
            </div>
        </>
    );
}

It will create a UI like this.
I want to get the tags from useTags whenever i click on the button. Unfortunately it is returning undefined.

And also wanted to know the performance of the above code. Expecting positive results.

Thank you for the community support
The end result

Is there some framework to use components on HTML documents?

Do you know about some framework I can use to create components on HTML documents (*.html)?

For instance, I have a website with multiple html documents (page1.html, page2.html, page3.html, etc.) and each document contains a header and a footer section, the problem is that if I want to make some changes to the footer I have to update every html document. I would rather prefer that these html documents had a “Footer” component like on Angular and update a single instance of that component.

I know about Angular, React or Vue, but I was wondering if there’s something simpler than those robust frameworks, and with a low learning curve.

getting the text input from html has problems

problem: i wanted it so when i click the submit button it would set the user first name to what was in the html text input but it would not get it and instead throw an error

let user={
firstName : "",
lastName : "",
fullName: function(){
return this.firstName+" "+this.lastName;
},
age: 0

};
document.getElementById("submit").onclick = function(){
user.firstName = document.querySelector('text').value
console.log(user.firstName)
}

I also tried changing the document query Selector to get Element By Id

How to remove transform style in draggable element?

I have a simple draggable element using cdk drag in angular ,

Now when I drag the element I have the following

<div _ngcontent-hnf-c31="" cdkdrag="" class="cdk-drag" style="left: 25.8912%; top: 35%; transform: translate3d(138px, 105px, 0px);">
</div>

When I try to remove the transform translate3d the element becomes undraggable.

Expected result

`<div _ngcontent-hnf-c31="" cdkdrag="" class="cdk-drag" style="left: 25.8912%; top: 35%"></div>`

and the element should be draggable

HTML

` <div *ngFor="let item of draggableElements">
            <div cdkDrag [innerHTML]="item.content" [style.left.%]="item.left" [style.top.%]="item.top" (cdkDragMoved)="updatePosition(item, $event)"></div>
        </div>`

I tried the following

 updatePosition(item: any, event: any): void {
    const containerElement = document.querySelector('.interactive-image-container');
    const containerWidth = containerElement!.clientWidth;
    const containerHeight = containerElement!.clientHeight;
    const positionX = (event.distance.x + event.source._dragRef['_passiveTransform'].x) / containerWidth * 100;
    const positionY = (event.distance.y + event.source._dragRef['_passiveTransform'].y) / containerHeight * 100;
    item.left = positionX;
    item.top = positionY;
    
      const draggableElement = event.source.element.nativeElement;
      draggableElement.style.transform = ''; // Remove the transform style
  }

But the above solution makes the element undraggable at all