How to Identify Buildings from a Map Image Using JavaScript

I am working on a project where I need to identify buildings from a map. This could be a static map taken from an image or a dynamic map rendered in the browser. My main goal is to extract information about buildings, such as their outlines or coordinates, from the map.

I am looking for a JavaScript-based solution that can help me achieve this. I am open to using libraries or APIs that could simplify the process, but I’m not sure where to start or what would be the most effective approach.

Here are some specific questions I have:

Are there any JavaScript libraries or APIs specifically designed for analyzing map images to identify buildings?
How can I extract building outlines or coordinates from a map image using JavaScript? Are there any specific techniques or algorithms that are recommended for this purpose?
If I am working with a dynamic map (e.g., Google Maps, OpenStreetMap), what tools or APIs could I use to identify buildings in real-time as the map changes?
Are there any examples or tutorials that demonstrate how to identify buildings from a map image using JavaScript?
Any advice, tutorials, or pointers to relevant documentation would be greatly appreciated. I am especially interested in any open-source tools or libraries that could help with this task.

Thank you in advance for your help!

I tried to use TensorFlow.js to process map images and identify buildings by their outline or coordinates. My approach involved trying to train a model with labeled images of maps where buildings were clearly marked. I hoped that the model would learn to recognize similar patterns in new map images, but even at a basic level I was not successful.

function getMapDataSomehow() {
    const markers = [
        { lat: 39.9334, lng: 32.8597 },
    ];
    return markers;
}

function convertMapDataToTensors(mapData) {
    const markerPositions = mapData.map(marker => [marker.lat, marker.lng]);
    return tf.tensor2d(markerPositions);
}

function processTensorsWithTensorFlow(tensors) {
    console.log('Tensor shape:', tensors.shape);
    tensors.print();
    
    const normalizedTensors = normalizeTensor(tensors);
    normalizedTensors.print();
    
}

function normalizeTensor(tensor) {
    const minLat = 36.0;
    const maxLat = 42.0;
    const minLng = 26.0;
    const maxLng = 45.0;
    
    const normalizedTensor = tensor.sub(tf.tensor([minLat, minLng])).div(tf.tensor([maxLat - minLat, maxLng - minLng]));
    return normalizedTensor;
}

document.getElementById('processMap').addEventListener('click', () => {
    const mapData = getMapDataSomehow();
    const tensorData = convertMapDataToTensors(mapData);
    processTensorsWithTensorFlow(tensorData);
});

validation input on multiple fields [duplicate]

I have the following code:

<div class="col-md-2"><label class="lb">item1</label><input class="form-control pesoformat" type="number" name="peso[]" value="0.00" min="0.00" max="1.00" step="0.01" placeholder="0.00" required >
                                                      
</div>

  <div class="col-md-2"><label class="lb">item2</label><input class="form-control pesoformat" type="number" name="peso[]" value="0.00" min="0.00" max="1.00" step="0.01" placeholder="0.00" required >
                                                      
</div>


<script>
var numberElement = document.querySelector(".pesoformat")                                       numberElement.addEventListener('change',alterNumber);
function alterNumber(event){
var el = event.target;
var elValue = el.value;
el.value = parseFloat(elValue).toFixed(6);
}
</script>

the function works only on item1 input field while on the second one it doesn’t…

where i’m wrong?

Random Line Appeared In VSCode

Not sure how or why but this black line/seperator appeared in my VSCode Editor, it seems the seperate thee code and the parent function. I want to get rid of it but I’m not sure how can I do that. I’m looking forward for solutions.
The problem

I looked through settings, and searched possible fixes but I couldn’t find anything related to this.

React Native Google Admob Native Ads

I need to use AdMob native ads in my React Native project, but I am unable to find a package for it. All the packages that are available include every type of ad except for AdMob native ads. How can I use Google native ads in React Native? Which package should I use for this? The package I am currently using is giving me an error: https://www.npmjs.com/package/react-native-admob-native-ads.
ERROR Ad failed to load {“code”: 0, “domain”: “com.google.android.gms.ads”, “message”: “Internal error.”}

How to always get the same number from a changable number?

i have an array which stores books, and i want to show a fixed number of those books, the array length is changable, so how would i always end up with the same number ? based on the length of the array? and increase that number each time a button is clicked ?

how i would want the functionality of my page:

“the shown items is 10, and always 10, and then everytime the button is clicked i would show 10 more, if the last books aren’t less than 10, then i would show them

what i want is this:

function BooksContainer(){
const itemLength = booksData.length

const [booksShown,setBooksShown] = useState(fixedItemLength)

return (
   booksData.slice(0,booksShown).map(()=>{
      return <Books>
    })

   <button onClick={setBooksShown((prev)=> prev + fixedItemLength)}>Show More</button>)
}


writing the question, i think im approaching the problem wrongly, thank you in advance

How to change button background color, on click, infinitely in javascript or css?

I have created a button that changes the background color to gradient and when I double click it, it returns back. When I click the button, it changes the color of itself to gradient, but when I double click it, the button doesn’t return back, it just shows the gradient. Can you help me to solve this problem?

I tried some javascript code, that I found in stack overflow. But it is not working.

Dynamically change background based on active slide in React Swiper

I’m building a React application using the Swiper component to display a carousel of movie cards. I want to dynamically change the background of the entire body or a specific div within the app component based on the currently active movie slide.

Here’s the relevant code:

CardSlider.jsx:

import React from 'react';
import Swiper from 'swiper/react';
import 'swiper/css';
import 'swiper/css/navigation';
import 'swiper/css/free-mode';
import 'swiper/css/autoplay';
import { FreeMode, Autoplay, Navigation } from 'swiper';

const CardSlider = ({ movies }) => {
  return (
    <>
      <Swiper
        slidesPerView={7.5}
        spaceBetween={30}
        freeMode={true}
        modules={[FreeMode, Autoplay, Navigation]}
        className="mySwiper"
        autoplay={{ delay: 5000, disableOnInteraction: false }}
      >
        {movies.map((movie, i) => (
          <SwiperSlide key={i}>
            <img src={`${poster_url}${movie.poster_path}`} alt="" />
          </SwiperSlide>
        ))}
      </Swiper>
    </>
  );
};

export default CardSlider;

App.jsx:

import React, { useEffect, useRef } from 'react';
import Header from './components/header/header.jsx';
import useStore from './store/store.js';
import CardSlider from './components/cards-slider/card-slider.jsx';

const App = () => {
  const { movies, fetchMovies } = useStore();
  const backgroundRef = useRef(null);

  useEffect(() => {
    fetchMovies();

    const handleSlideChange = (swiper) => {
      const activeSlide = swiper.activeIndex;
      // Implement logic to update background based on active slide using backgroundRef
      console.log('Active slide index:', activeSlide);
    };

    const swiper = backgroundRef.current; // Assuming reference points to Swiper instance
    if (swiper) {
      swiper.on('slideChange', handleSlideChange);
    }

    return () => {
      if (swiper) {
        swiper.off('slideChange', handleSlideChange);
      }
    };
  }, [fetchMovies]);

  console.log(movies);

  return (
    <div ref={backgroundRef}>
      <Header />
      <CardSlider movies={movies} />
    </div>
  );
};

export default App;

store.js:

import { create } from 'zustand';
import axios from 'axios';
import { api_key, url } from '../api/config.js';

const useStore = create((set) => ({
  movies: [],
  fetchMovies: async () => {
    const { data: { results } } = await axios.get(`${url}discover/movie?page=1&api_key=${api_key}&language=ru-RU`);
    set({ movies: results });
  },
}));

export default useStore;

Treat parsed JSON as HTML instead of text

Consider this simple code below

When I parse the content and get the “txt” with JSON.parse(e.data).choices[0].delta.content; then it works fine if it is plain text. However, there are some simple HTML tags in the response like <strong> etc. which don’t render as HTML in the browser.

I don’t know how to render it as it is. I realize that the chunks of data, when they arrive, may not have closing HTML tags in them and may also have incomplete HTML tags, but when the stream ends, then all is well usually.

How do I ensure that the browser treats the “txt” content as HTML and not as text? The variable thisWebPath is well set and does get streamed data back in JSON

Thanks in advance

function sendMsg(msg) {

    var formData = new FormData();
    formData.append('msg', msg);
    formData.append('user_id', USER_ID);
    fetch(thisWebPath + '/send-message.php', {method: 'POST', body: formData})
        .then(response => response.json())
        .then(data => {
            let uuid = uuidv4()
            const eventSource = new EventSource(thisWebPath + `/event-stream.php?chat_history_id=${data.id}&id=${encodeURIComponent(USER_ID)}`);
            appendMessage(BOT_NAME, BOT_IMG, "left", "", uuid);
            const div = document.getElementById(uuid);

            eventSource.onmessage = function (e) {
                if (e.data == "[DONE]") {
                    msgerSendBtn.disabled = false;
                    document.getElementById("userSendButtonAV").value="Send";
                    var elemB = document.getElementById("userSendButtonAV");
                    elemB.value = "Send";


                    document.getElementById('userMessageAV').placeholder='Enter your message now...';
                    document.getElementById('userMessageAV').disabled = false;
                

                    eventSource.close();
                } else {
                    
                    //original code  let txt = JSON.parse(e.data).choices[0].delta.content
                    if (isJsonString(e.data)) {
                        let txt = JSON.parse(e.data).choices[0].delta.content;

                    if (txt !== undefined) {
                        div.innerHTML += txt.replace(/(?:rn|r|n)/g, '<br>');
                    }
                } 
                        
            }
            };
            eventSource.onerror = function (e) {

                var elemC = document.getElementById("userSendButtonAV");
                elemC.value = "Send";

                
                msgerSendBtn.disabled = false;
                document.getElementById('userMessageAV').placeholder='Enter your message now...';
                document.getElementById('userMessageAV').disabled = false;
            
                //console.log(e);
                eventSource.close();
            };
        })
        .catch(error => console.error(error));


}

I am expecting the text to be handled like HTML

Facing an error in using solc module for compiling my HelloWorld contract through JS

[email protected] start

node app.js

node:internal/modules/cjs/loader:1152
throw err;
^

Error: Cannot find module ‘solc’

/FACING THIS ERROR/

This is my code and I tried running it with import statement too

const solc = require('solc')
const fs = require('fs')

const CONTRACT_FILE = 'HelloWorld.sol'

const content = fs.readFileSync(CONTRACT_FILE).toString()

const input = {
  language: 'Solidity',
  sources: {
    [CONTRACT_FILE]: {
      content: content
    }
  },
  settings: {
    outputSelection: {
      '*': {
        '*': ['*']
      }
    }
  }
}

const output = JSON.parse(solc.compile(JSON.stringify(input)))

for (const contractName in output.contracts[CONTRACT_FILE]) {
  console.log(output.contracts[CONTRACT_FILE][contractName].evm.bytecode.object)
}

VUE JS Multi Dimensional Issue

when try to update inner array value with index, it reflects all parent array elements.

this.data = [{files:[{url:''},{url:''}]}, {files:[{url:''},{url:''}]}]; 

this.data[1]['files'][1]['link'] = 'new link';

console.log(this.data);
[{files:[{url:''},{url:'', link:'new link' }]}, {files:[{url:''},{url:'', link:'new link'}]}];

value add/update to all parent items

need to show

[{files:[{url:''},{url:''}]}, {files:[{url:''},{url:'', link:'new link'}]}];

value add/update to only the parent index = 1

React/Next.js – Conditional className Best Practice

Coming into Next.js from Vue, I am struggling a little with the most effective practice.

The task at hand is to have an input field that takes an email, check if the email is in correct form or not and apply different CSS rules to the input field using an input.module.css file classes.

Below input field checks if the “email” exists at all, if it doesn’t it applies the input.idle class to the field. If it exists, it checks if the email is valid using a separate utility class I wrote ( not sharing it’s code due to irrelevance to the question ) and applies either input.valid or input.invalid depending on if the email is valid indeed.

<input type="text" placeholder="Email" value={email} onChange={handleEmail} className={`w-5/12 ${input.shape} ${input.idle} ${email ? (emailValid ? input.valid : input.invalid) : input.idle}`}/>

Now to do any of this, in my export function I wrote the code as follows:

const [email, setEmail] = useState<string>('');
const handleEmail = (e: ChangeEvent<HTMLInputElement>) => {
    const newVal = e.target.value;
    setEmailValid(StringValidator.isValidEmail(newVal));
    setEmail(newVal);
}

const [emailValid, setEmailValid] = useState<boolean>(false);

Something makes me feel like this isn’t the best practice to handle such a situation since the input field codes className could get very bloated had I wanted to check for one more situation. Is there any other way to do this which makes my code more readable?

How to use threejs version 0.83.0 with aframe version 1.3.0?

I want to use aframe version 1.3.0 with threejs version 0.83.0 because of one script i got online and it will work with version 0.4.0 and i want to add it in version 1.3.0. Can anyone help me with the problem and please tell me if there is another way to do it.

I have tried to use the script in multiple aframe versions and it works fine from version 0.4.0 to version 0.9.0

Do global variables carry their values assigned in one function in all other functions too

I am a new in programming.
I have a question about global variables. I am a little confused on how the variable I declared globally and assigned it a value in my first button handler function works in other functions too.

let currentAccount;

btnLogin.addEventListener('click', function (e) {
  e.preventDefault();
  currentAccount = accounts.find(
    acc => acc.username === inputLoginUsername.value
  );
  if (currentAccount?.pin === Number(inputLoginPin.value)) {
    //Display UI AND Message
    labelWelcome.textContent = `Welcome back ${
      currentAccount.owner.split(' ')[0]
    }`;
    containerApp.style.opacity = 100;
    //Clear inputfields
    inputLoginUsername.value = inputLoginPin.value = '';
    inputLoginPin.blur();
    //Display Movements
    displayUI(currentAccount);
  }
});

btnTransfer.addEventListener('click', function (e) {
  e.preventDefault();
  const amount = Number(inputTransferAmount.value);
  const receiverAcc = accounts.find(
    acc => acc.username === inputTransferTo.value
  );
  inputTransferAmount.value = inputTransferTo.value = '';
  if (
    amount > 0 &&
    receiverAcc &&
    currentAccount.balance >= amount &&
    receiverAcc?.username !== currentAccount.username
  ) {
    currentAccount.movements.push(-amount);
    receiverAcc.movements.push(amount);

    displayUI(currentAccount);
  }
  console.log(currentAccount);
});

I thought I had to reassign currentAccount variable because was declared in another function and we don`t have access to the variables or in this case the values of other functions variables.

Hi guys, i have seen this example on w3schools and wanted to do same but i get an error although i did exactly same with the website

let x = document.getElementById("txt");
setTimeout(function(){ x.value="2 seconds"}, 2000);
setTimeout(function(){ x.value="4 seconds" }, 4000);
setTimeout(function(){ x.value="6 seconds" }, 6000);
 <input type="text" id="txt">

Uncaught TypeError: Cannot read properties of null (reading ‘value’) ( I get this )
I searched for solution but couldn’t find anywhere. Would be glad if anyone can help me

I wanted to see 2 seconds, 4 seconds and 6 seconds consecutively in input.

Regarding password validation in php

row = mysqli_fetch_assoc($result);
$hashedPassword = $row['pass'];
$enteredPassword = $_POST['password'];

if (password_verify($enteredPassword, $hashedPassword)) {
header("Location: a.php");
exit();`

Well I used the above piece of code for a login validation. ‘pass’ in the $row is how i stored the password in my database table.

Even when i entered the password correctly it displays password is incorrect where i used

echo '<script>
alert("Incorrect password. Please try again.");
window.location.href="login.php";
</script>

to be displayed when password is not matching with the stored password in the database. Why is that and how to solve this?