Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

90
Visualizações
Creating random coordinated svg circles with distance between them

I am trying to create randomly placed SVG circles, but I don't want them to be too close to each other. I am using firestore for the backend and d3.js to create circles. Each circle is placed due to its "xValue" and "yValue" in firebase, which are generated using Math.random. These values (coordinates) should be created in a special different way to avoid too close circles.

My first approach was to use Math.random again but check all existing xValues and yValues to find the distance between the circle that I am about to create, then if the distance is lower than 80, increase Math.random value 100. It doesn't work

function createRandomCoordinates() {
  
  var coordinates = [];

  getDocs(collection(db, "circles")).then((querySnapshot) => {
    querySnapshot.forEach((doc) => {
      coordinates.push({ ...doc.data() });
    })
 }); 
  
   
  let randomXValue = Math.floor(Math.random()*1200);
  let randomYValue = Math.floor(Math.random()*1200);

  var distances = [];
  
  for (let i = 0; i < coordinates.length; i++) {
    var a = coordinates[i].xValue - randomXValue;
    var b = coordinates[i].yValue - randomYValue;
    var distance = Math.sqrt(a * a + b * b);
    distances.push(distance);
    
    if(distances.some((e) => e < 80)){
    return {
       randXVal: randomXValue + 100,
       randYVal: randomYValue + 100
}
   }else {
    return {
      randXVal: randomXValue,
      randYVal: randomYValue
    }
  }
}
} 
console.log(createRandomCoordinates().randXVal,createRandomCoordinates().randYVal )
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

getDocs is an asynchronous call, since it needs to read data from the server. While the data is being read, your main code continues to run so that the user can continue using the app. Then when the data is available, your callback is invoked with that data.

In practice this means that your for (let i = 0; i < coordinates.length; i++) { loop is called before any of the coordinates.push({ ...doc.data() }) happened, so it's always looping over an empty array.

The solution is always the same: the code that need the data has to be inside the callback, or be otherwise synchronized (like through a callback or a promise).

The simplest fix is to move the code that uses the coordinates into the callback, after the loop:

function createRandomCoordinates() {
  
  return getDocs(collection(db, "circles")).then((querySnapshot) => {
    const coordinates = querySnapshot.docs.map((doc) => doc.data());

    let randomXValue = Math.floor(Math.random()*1200);
    let randomYValue = Math.floor(Math.random()*1200);

    var distances = [];
  
    for (let i = 0; i < coordinates.length; i++) {
      var a = coordinates[i].xValue - randomXValue;
      var b = coordinates[i].yValue - randomYValue;
      var distance = Math.sqrt(a * a + b * b);
      distances.push(distance);
    
      if(distances.some((e) => e < 80)){
      return {
        randXVal: randomXValue + 100,
        randYVal: randomYValue + 100
      }
    } else {
      return {
        randXVal: randomXValue,
        randYVal: randomYValue
      }
    }
  } //missing curly bracket
  }); 
} 

Also see:

  • Why Does Firebase Lose Reference outside the once() Function?
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda