Google Maps API v3 JS: Get KML Layer featureData from entered coordinates

I have a Google Map with multiple KML files loaded, mainly polygons. I want to be able to pass a function coordinates and I need to get back the featureData, like when you click on a location. The simplest way I can describe this is to have the user enter geocoordinates, place a marker and get the KML Layer featureData for where the marker is placed. I would preferably like to do all this in JS but am open to all suggestions.

I have been crafting Google queries for hours and have found nothing that does this. I have tried all the trigger event options but obviously I can only access the Marker’s event and not the KML Layer event or details. I have also played with using DomEvents and screen x,y coordinates and simulating a click but this did not work either, also it did not work with receiving geo coordinates but I was desperate.

Javascript created SVG shows in inspector but not on screen

Here is the test code

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
      
    </style>
    <title>xyz</title>
  </head>
  <body>
    <div>
      <svg id="mysvg" xmlns="http://www.w3.org/2000/svg"
       width="360" height="360">
    <line x1="1" y1="1" x2="359" y2="359" stroke="black"/>
    <circle cx="100.00" cy="100.00" r="25.17" fill="#00ffff"
        stroke="red"/>
      </svg>
    </div>
  </body>
  <script>    
    // used all over
    const svgNS = "http://www.w3.org/2000/svg";
    let svg_el = document.getElementById("mysvg");
    let sh_el = document.createElementNS(svgNS, "rect");
    sh_el.setAttributeNS(svgNS, "x", "150");
    sh_el.setAttributeNS(svgNS, "y", "150");
    sh_el.setAttributeNS(svgNS, "stroke", "blue");
    sh_el.setAttributeNS(svgNS, "width", "10");
    sh_el.setAttributeNS(svgNS, "height", "40");
    svg_el.appendChild(sh_el);
  </script>
</html>

In Firefox using the inspector I see the line, circle and rect elements but the rect does not display. I’ve looked at other Stackoverflow answers and I don’t think it’s a name-space issue. My best guess is that the DOM is not updated but I don’t know how that could happen

how to mimic developer console style intervention event

I am trying the trigger resize event of a canvas. However, I am not very good at javascript. but I realize that, If I toggle width check-box in computed section of developer console, canvas slowly resize itself. Now I want to know how to mimic that event.

enter image description here

I tried ::after ::before tags in css but it didn’t work.

Push elements to array returned by a promise [duplicate]

I have an asynchronous API call that returns me an array from the backend:

const call = PlayListsAPI.songsFromPlayList("default")
console.log(call)

As I suppose the returns at this moment is that I expect:

Promise { <state>: "pending" }
<state>: "fulfilled"
<value>: Array(3) [ {…}, {…}, {…} ]

The problem come when try to push the content of the array into other, once I get the resolved data from the promise, like this:

const dataFromPromise = []

const call = PlayListsAPI.songsFromPlayList("default")
    .then(data => {
      for (const song of data) {
        dataFromPromise.push(song)
      }
    })

Doing this, the dataFromPromise array is empty after the .then call:

Array []

And the promise is still ‘pending’:

Promise { <state>: "pending" }
<state>: "fulfilled"

Where am I failing?

Thanks in advance, if another info is needed tell me 🙂

Code and Level review for Quizz Project in Javascript

As I’m still on my journey to learn properly the basics of Javascript before getting into Angular. I tried a new Challenge; a Quizz but slightly differently.

  1. The user can enter his username.
  2. I display the username and ask the user to pick a subject.
  3. Once the subject is picked and displayed, the player has to answer 3 random questions on the subject.
  4. A dialog with his final score is displayed then the page is reloaded to play again.

NOTE: My question objects have 4 fields; question, options (string array), answer and subject.
My 2 questions/requests:

  • Is there a way to update the score on the view in real time?
  • Would it be possible to have a feedback on what I did (ie: How amateur is my code :’) and if there are any advices to raise the quality of it).

Thank you.

HTML:

<main>
        <h1>Quizz project</h1>

        <div class="content-header-section"></div>
        <div class="quizz-section"></div>

        
        <div class="username-section">
            <h2>Hi there!</h2>  
            <form action="" class="username-form">
                <label for="username-input">Enter your name: </label>
                <input type="text" id="username-input">
                <input type="submit" value="Start the quizz">
            </form>
            <template class="user-template"><h2>Hi there!</h2> </template>
        </div>
        

        <div class="subject-section">
            <template class="subject-template">                 
                <div class="subject-option">
                    <input class="subject-btn" type="button" value="lo">
                </div>
            </template>
            <template class="pickedSubject-template"><h3>You picked this subject</h3> </template>
        </div>


        <div class="question-section">
            <template class="question-template">
                <div class="question-asked"><p>Question?</p></div> 
                <div class="question-options"></div>              
            </template>
        </div>

    </main>

JAVASCRIPT:

const contentHeaderSection = document.querySelector(".content-header-section");
const quizzSection = document.querySelector(".quizz-section");
const usernameSection = document.querySelector(".username-section");
const subjectSection = document.querySelector(".subject-section");

const usernameForm = document.querySelector(".username-form");

const userTemplate = document.querySelector(".user-template");
const subjectTemplate = document.querySelector(".subject-template");
const pickedSubjectTemplate = document.querySelector(".pickedSubject-template");
const questionTemplate = document.querySelector(".question-template");



subjects = ["History", "Music"];
let pickedSubject;
let quizz;
let currentQuestion;
let answerCounter;
let score;

//Check and act once the user enter its username
usernameForm.addEventListener('submit', e =>{
    e.preventDefault();
    const usernameVal = document.getElementById("username-input").value;
    if(usernameVal=="" || usernameVal==undefined){
        alert("Please enter your username.");
    }else{
        initializeValues();
        updateUsernameSection(usernameVal);
        createSubjectOption();
    }
});

const initializeValues = ()=>{
  pickedSubject="";
  currentQuestion="";
  score = 0;
  answerCounter = 0;
};

//hide the form for username and replace it by a welcome text with the username
const updateUsernameSection = (name)=>{
   usernameSection.style.display= "none";
   const userCopy = userTemplate.content.cloneNode(true);
   userCopy.querySelector("h2").textContent = `Hi there, ${name}!`;
   contentHeaderSection.appendChild(userCopy);
};

//create a dispaly for each subject of quizz
const createSubjectOption = ()=>{
    subjects.forEach(subject => {
        const subjectCopy = subjectTemplate.content.cloneNode(true);
        subjectCopy.querySelector(".subject-btn").value = subject;        
        subjectSection.appendChild(subjectCopy);
    });   
}

//When user pick a subject
const subjectButtonHandler = e=>{ 
  pickedSubject = e.target.value;
  displayPickedSubject();
  quizzMaker();
}

//hide subject options and display the subject picked
const displayPickedSubject = ()=>{
  subjectSection.style.display = "none";
  const pickedSubjectCopy = pickedSubjectTemplate.content.cloneNode(true);
  pickedSubjectCopy.querySelector("h3").textContent = `
  You picked: ${pickedSubject}. Your current score is: ${score}.`;
  contentHeaderSection.appendChild(pickedSubjectCopy);
  
}

//Makes the quizz, display the question, handle the answer
const quizzMaker = ()=>{
    const condition = (element) => element.subject.toUpperCase() === pickedSubject.toUpperCase();
    quizz = getQuestionsWithCondition(questions, condition, 3);
    questionDisplay(quizz, answerCounter);
}


const questionDisplay = (arr, index)=>{
  quizzSection.innerHTML="";
  currentQuestion = arr[index];
  const questionCopy = questionTemplate.content.cloneNode(true);
  questionCopy.querySelector("p").textContent = currentQuestion.question;
  createOptionButtons(questionCopy);
  quizzSection.appendChild( questionCopy);
}

const createOptionButtons = (questionCopy)=>{
  currentQuestion.options.forEach(option => {
    const button = document.createElement("button");
    button.textContent = option;
    button.value = option;
    questionCopy.querySelector(".question-options").appendChild(button);
  });
}

const getQuestionsWithCondition = (arr, condition, count) => {
  const res = [];
  while (res.length<count){
    const randomElement = arr[Math.floor(Math.random()*arr.length)];
    if(condition(randomElement) && !res.includes(randomElement)){
      res.push(randomElement);
    }
  }
  return res;
};


const quizzHandler = (e)=>{
  if(e.target.value == currentQuestion.answer){
    ++score;
  }
  ++answerCounter;
  if(answerCounter<3){
  questionDisplay(quizz, answerCounter);
  }
  else{
    alert(`Quizz is over! Here's your final score:${score}`);
    window.location.reload();
  }
};

subjectSection.addEventListener('click', e=> e.target.tagName==='INPUT' && subjectButtonHandler(e));
quizzSection.addEventListener('click', e=> e.target.tagName==='BUTTON' && quizzHandler(e));

NodeJS POST request returning bad json error, but is it?

I am trying to call Google NEST API for the thermastat, but im getting thw following error:

{
    "error": {
      "code": 400,
      "message": "Invalid JSON payload received. Unknown name "params[heatCelsius]": Cannot bind query parameter. Field 'params[heatCelsius]' could not be found in request message.",
      "status": "INVALID_ARGUMENT",
      "details": [
        {
          "@type": "type.googleapis.com/google.rpc.BadRequest",
          "fieldViolations": [
            {
              "description": "Invalid JSON payload received. Unknown name "params[heatCelsius]": Cannot bind query parameter. Field 'params[heatCelsius]' could not be found in request message."
            }
          ]
        }
      ]
    }
  }

Here is how I am creating the post data:

    var temp = req.query.temp;
    var coolOrHeat = req.query.coolHeat;

    let celsius = (temp - 32) * 5 / 9;

    var jsonDataObj;

    if (coolOrHeat == "heat") {
        jsonDataObj = {
            command: 'sdm.devices.commands.ThermostatTemperatureSetpoint.SetHeat',
            params: {
                heatCelsius: celsius
            }
        }
    }

    if (coolOrHeat == "cool") {
        jsonDataObj = {
            command: 'sdm.devices.commands.ThermostatTemperatureSetpoint.SetCool',
            params: {
                coolCelsius: celsius
            }
        }
    }

Here is my POST req

            var urlSetTemp = 'https://smartdevicemanagement.googleapis.com/v1/enterprises/' + projectId + '/devices/' + thermId + ':executeCommand';

            request.post({
                headers: {
                    'content-type': 'application/json',
                    'Authorization': 'Bearer ' + accessToken
                },
                form: jsonDataObj,
                url: urlSetTemp
            }, function (error, response, body) {

                var json = JSON.parse(body);
                console.log("res: ", json);


                res.json({
                    'json': json,
                    'ack': "success",
                    'body': jsonDataObj
                });
            });

Google’s doc: https://developers.google.com/nest/device-access/traits/device/thermostat-temperature-setpoint#setheat

Finally, in postman, im good, it works, but not in node.

What exactly am I doing wrong?

enter image description here

Dropping an element to another row of elements fails to work when dropped in front of first or after last element

I am trying to build a very simple drag and drop website. The user can drag a preset ‘section’ from a sidebar which contains different numbers of columns, referred to as ‘cells’. The user drags it onto a canvas and can rearrange the cells and sections. Sections are in rows, and are the parent of these cells.

The issue is that the user is not able to move a cell from one section to another section if they try to drop it in front of the first cell of that section or after the last cell of that section. Anything in between is working.

Code snippet:

             if (userOption.classList.contains('gen-section')) { // Different actions depending on class of element
                let dropPosition = ev.clientY;
                let elements = document.querySelectorAll('.gen-section');
                let closestElement = null;
                elements.forEach((element) => {
                    if (!closestElement || Math.abs(dropPosition - element.getBoundingClientRect().top) < Math.abs(dropPosition - closestElement.getBoundingClientRect().top)) {
                        closestElement = element;
                    }
                });

                if (dropPosition < closestElement.getBoundingClientRect().top + closestElement.offsetHeight / 2) {
                    // Insert before the closest element if the drop position is above its midpoint
                    closestElement.parentNode.insertBefore(userOption, closestElement);
                } else {
                    // Insert after the closest element if the drop position is below its midpoint
                    closestElement.parentNode.insertBefore(userOption, closestElement.nextSibling);
                }
            } else if (userOption.classList.contains('gen-cell')) {
                let dropPositionX = ev.clientX;
                let elements = document.querySelectorAll('.gen-cell');
                let closestElement = null;

                elements.forEach((element) => {
                    if (!closestElement || Math.abs(dropPositionX - element.getBoundingClientRect().left) < Math.abs(dropPositionX - closestElement.getBoundingClientRect().left)) {
                        closestElement = element;
                    }
                });

                let hoveredElement = ev.target;
                let closestCell = hoveredElement.closest(".gen-cell");
                let closestSection = hoveredElement.closest(".gen-section");

                if (closestSection.hasChildNodes()) {
                    if (Math.abs(dropPositionX - closestElement.getBoundingClientRect().left) < Math.abs(dropPositionX - closestElement.getBoundingClientRect().right)) {
                        // Insert before the closest element if the drop position is left of its midpoint
                        closestElement.parentNode.insertBefore(userOption, closestElement);
                    } else {
                        closestElement.parentNode.insertBefore(userOption, closestElement.nextSibling);
                    }
                } else {
                    // Insert into an empty section
                    hoveredElement.appendChild(userOption);
                }
            }

Also, when I drag and drop a cell inside of a section that only contains itself, it drops itself into another section below when it should stay where it is. I am not sure where I have gone wrong in my logic, or if I am missing a piece of code which I have completely overlooked.

Nextjs: how to debug production locally because development is working perfectly

My nextjs setup is running perfectly in development.
When do a build, all is building as it should.
But when we serve production locally we get

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined.

Now, I know that it’s probably because of a mixup of named imports or something but since it’s such a large application, isn’t there a way to debug production locally?

I already saw the documentation regarding NODE_OPTIONS=’–inspect’

thanks!

Why isn’t react router passing down the params using match or even useParams?

Hello I’m trying to get the params from my route to a component two components down.

         <Route path='/Projects'>
            <Route path='' element={<ProjectsList
              loggedIn={loggedIn}
              loggedInUsername={username}
              setSelectedProject={setSelectedProject}/>}
            />

            <Route path=":id" element={<ProjectSubPage
              selectedProject={selectedProject}/>}
            />
        </Route>

I’ve tried putting the route with the path=”:id” outside of the route. I have tried moving the route to a component down but then it can’t find it. I tried using exact. I tried using nested paths.

How do I parse serialized protobuff messages in js?

I have a flask app that sends a large (100mb) binary message to js. I can send the files easily, however, I can’t seem to decode my message in js. I am using this library:

https://github.com/protobufjs/protobuf.js

The message is encoded by python using the standard code generator protoc.

The encoded message looks something like ""res = u0008�Iu0008�u0015u0008�u0016u0008�u0015u0008�)u0008�? [...]"

According to the documentation I’ve read so far, I need to convert res before I can decode. The following fails:

j = new TextEncoder("utf-8").encode(res);
protoMsg.decode(j);

I get the error message:

Uncaught Error: invalid wire type 6 at offset 198

How to prevent other buttons acting when a button is acting Javascript

I created a game like gold miner game. So when i click the gift, the tool will go to the gift and pick it. Ans i set up 5 gifts around. But when i click the first gift and other gifts in the same time, the tool will come to the last gift that i has just clicked. So how to prevent the tool execute other buttons actions when it’s still execute the first button.

I don’t know how to resolve it

How to pause and restart a clock in React

Hello StackOverflow community.

I am just starting with learning react and I came across this challenge, where we have to display the current time, with a button to Pause/Restart the time. But the catch is on clicking the pause button it should pause the time, and again on clicking the button it should restart the clock from the same paused time.

Please note that the clock should start from the paused time and not the current time.

Below is my code.

import "./App.css";
import { useEffect, useState } from "react";

function App() {
  const [time, setTime] = useState(new Date().toLocaleTimeString());
  const [pause, setPause] = useState(false);

  useEffect(() => {
    let timer = setInterval(() => {
      if (!pause) {
        setTime(new Date().toLocaleTimeString());
      }
    }, 1 * 1000);
    return () => clearInterval(timer);
  }, [pause]);

  return (
    <div className="m-2 p-2 flex">
      <h1 className="m-1 p-1">{time}</h1>
      <button
        className="m-1 p-2 bg-slate-200 rounded-lg shadow-lg font-semibold"
        onClick={() => setPause(!pause)}
      >
        {pause ? "Start" : "Pause"}
      </button>
    </div>
  );
}

export default App;

I am not able to get the logic on how to restart the clock from the paused time and not the current time.
Any help is appreciated.

Can you convert a text HTML Element to a select?

I have an HTML Element on a page that is a text/input box. I am looking to convert this type to a select/drop down but have not had any luck figuring out if this is possible. I am fairly new to javascript, and working with the DOM.

Is there a simple way to convert a HTML Element to a select?

I have tried looking at articles like this, but updating the type does not change anything in the UI:
Change Input type HTML using JavaScript

I dont think the above is what I am actually trying to do since this is trying to change the input type and not changing the type of element.

I am happy to provide screenshots to better explain, I am just not sure exactly what information would be helpful.

enter image description here

I have tried looking at articles like this, but updating the type does not change anything in the UI:

This last link I think is what I am trying to do but this is for jQuery

Problems with fetching data on Express server

I created NodeJS server with Express.js and now I’m trying to make a request for it by fetch.

fetch("http://localhost:3001/api", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(formData),
  })
    .then((response) => response.json())
    .then((data) => {
      if (data.user) {
        alert(`Welcome, ${data.user.name}!`);
      } else {
        alert("User not found!");
      }
    })
    .catch((error) => {
      alert("Error fetching data:" + error);
    });

This is server part:

const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');

const app = express();
app.use(cors());
app.use(bodyParser.json());

const users = {
  AG0n1: {
    name: "AG0n1",
    status: "admin",
    email: "[email protected]",
    password: "111",
    phoneNumber: "+375293883088",
  },
  Teacher: {
    name: "Teacher",
    status: "admin",
    email: "admin",
    password: "test",
    phoneNumber: "+375293883088",
  },
  User: {
    name: "User",
    status: "user",
    test: "test",
  },
};

app.post('/api', (req, res) => {
  console.log("Received a POST request");
  const { email, password } = req.body;
  const user = Object.values(users).find((u) => u.email === email && u.password === password);
  if (user) {
    console.log(user)
    res.json({ user });
  } else {
    res.status(401).json({ error: 'Invalid credentials' });
  }
});


app.get('/api', (req, res) => {
  res.json(users);
});

But sometimes at random moment I get the following error:
Error fetching data:TypeError: Failed to fetch

At first glance, there seems to be no pattern to this error. Sometimes I get the expected result and sometimes this error.
Can you help me to solve this problem?

ChatGPT said that my code is normal and that I used middleware ‘cors()’. He didnt help me so i decided to ask this question here.

Vuetify 2 data table. Get row from given value

I’m using Vuetify 2 and I am trying to get the row values from a given value. I’m am using a barcode scanner as a keyboard input so I can change the packed quantity when the barcode is scanned. I am trying to use the Customer_barcode as the value to find the other data with in the same row.

The example date is received and stored in a object called “items:[]”
headers: [ { text: "Image", value: "image", sortable: false, }, { text: "Item", align: "start", value: "Line_Number" }, { text: "Part Number", value: "EI_Number" }, { text: "Qty ToPack", value: "Qty_Backordered" }, { text: "Qty Packed", value: "Qty_To_Ship" }, { text: "barcode", value: "Customer_barcode", align: " d-none" }, ]

I am then able to get the customer barcode using a text-field that grabs the barcode with a method using this function below. Then I would like to add the quantity each time a barcode is scanned by getting the row data and modifying it. But I am unable to get the rows’ data.

‘handleBarcodeInput(event) {

  const scannedbarcode = event.target.value;
  console.log("Detected Barcode:", scannedbarcode);
//   console.log("Detected length:", scannedbarcode.length);
  if (this.scannedbarcode.length <= 8) {
    this.barcode = "";
    return this.barcode;
  }
  if (this.scannedbarcode !== null && this.scannedbarcode.length >= 9) {
    const item = this.items.find(item => items.Customer_barcode === scannedbarcode);<- doesn't work
    console.log(item); <- undefined

    // scannedbarcode = "";
    // return scannedbarcode;
  }
}'

I cannot seem to find the answer to this question anywhere. Any help would be greatly appreciated. Thank you,