Transpose chords value doesn’t work normally in Javasript

I have 7 buttons, C D E F G A B , a textarea and an Original Key.

If I copy the lyrics “Fly me to the moon” into the textarea with its chords and press the E button once, it will go up a tone normally.
However, if I press the same button again, it will go up another tone.
What is wrong with the value, can someone explain to me?
Thank you in advance

const { transpose, Interval } = Tonal;

// Function to transpose chords in the text
function transposeChords(text, interval) {
return text.replace(/b([A-G][#b]?)(m|min|maj|dim|dim7|aug|sus|add)?([0-9]*)b/g, (match, root, type, number) => {
let chordType = type;

// Handle extended chords
if (number) {
chordType = chordType || '';
if (number.match(/d+/)) {
    chordType += number; 
}
}
    
try {
const  transposedRoot = transpose(root, interval);
const  transposedChord = transposedRoot + (chordType || '');
return transposedChord || match;
} catch (e) {
    console.error('Error transposing chord', match, e);
    return match;
}
});
}

// Function to handle transpose button click
window.transpose = function(padd) {
let interval = Interval.distance(window.originalKey, padd);
let lyrics = document.getElementById("textarea").value;
document.getElementById('textarea').value = transposeChords(lyrics, interval);
colorPads(padd);
};


//  Highlighted 17 Pads
function colorPads(padd) {
const buttons = document.querySelectorAll('.pads');
buttons.forEach(button => {
    if (button.dataset.padd === padd) {
        button.classList.add('blue');
    } else {
        button.classList.remove('blue');
    }
});
}


// Save original key when selected from dropdown
function originalKey_function() {
    const select_OrigKey = document.getElementById('originalKey_id');
    window.originalKey = select_OrigKey.value;
    colorPads(window.originalKey);
}


// Event listener for pads (17 buttons)
document.querySelectorAll('.pads').forEach(button => {
    button.addEventListener('click', () => {
    const padd = button.dataset.padd;
    window.transpose(padd);
    });
});

// Event listener for original key dropdown
document.getElementById('originalKey_id').addEventListener('change', originalKey_function);

// Initial setup
window.originalKey = 'C'; // Default original key
colorPads(window.originalKey);
body {
    font-family: Arial, sans-serif;
    background-color: #333;
    color: #ddd;
    text-align: center;
}

.pads_container {
    position:relative;
    top:2vmin;  
    display:flex;
    width:95%;
    left:1vmin;
    right:1vmin;
}

button.pads {
    padding: 1em;
    font-size: 3vmin;
    border: 1px solid #ccc;
    background: green;
    color: #fff;
    cursor: pointer;
}

button.pads.blue {
    background-color: #007bff;
    color: #fff;
}

button.pads:hover {
    background-color: #00a3d9;
}

#textarea {
    top:3em;
    position:relative;
    width:100%;
    background: #222;
    color: #ddd;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<script src="https://cdn.jsdelivr.net/npm/tonal/browser/tonal.min.js"></script>
<script>
  console.log(Tonal.Key.minorKey("Ab"));
</script>
</head>
<body>

<!-- Original Key -->
<div>
    <label for="originalKey_id">Original Key:</label>
    <select id="originalKey_id">
        <option value="C">C</option>
        <option value="D">D</option>
        <option value="E">E</option>
        <option value="F">F</option>
        <option value="G">G</option>
        <option value="A">A</option>
        <option value="B">B</option>
    </select>
</div>


<!-- 17 buttons -->
<div class="pads_container">
    <button class="pads" data-padd="C">C</button>
    <button class="pads" data-padd="D">D</button>
    <button class="pads" data-padd="E">E</button>
    <button class="pads" data-padd="F">F</button>
    <button class="pads" data-padd="G">G</button>
    <button class="pads" data-padd="A">A</button>
    <button class="pads" data-padd="B">B</button>
</div>




<textarea value="" id="textarea" rows="5" cols="25">
 D             G             A              D
Fly me to the moon, let me play among the stars
</textarea>
</div>



</body>
</html>

Besides Adobe Flash, are there any other drawing software options that can easily achieve the effects shown in the example?

imageExample

In Flash software, a vector graphic’s path and fill can be separated in this magical way, allowing for easy cutting of patterns, distorting boundaries or lines, and performing splices with just the black arrow tool (selection tool)… I cannot find any other software that can accomplish these same operations as effortlessly. In software like Photoshop and Illustrator, if one uses the pen tool to draw these elements, not only is the drawing process cumbersome, but their paths are closed, with strokes and fills connected together, making it extremely difficult to perform the same operations seen in the image… Currently, I feel that Flash (Animate CC) is the most user-friendly vector design software (?). At least for designers, Flash’s functionality allows ideas to be drawn out at the fastest speed… So, regarding the implementation of similar functionalities, are there any bottlenecks or technical difficulties in the software algorithms? Apart from Flash, I haven’t seen another piece of software use a simple tool (black arrow – selection tool) to so easily accomplish similar tasks.

Puppeteer with React – can’t fetch data (nextjs)

I have the following page on my website:

'use client';
import { useExam } from '@/api/exam/hooks';
import { Suspense } from 'react';

export default function ExamPdfPage({
  params: { id },
}: {
  params: { id: string };
}) {
  const { data: exam, isFetching, isSuccess } = useExam(id);

  if (isFetching) return <div>Loading</div>;
  if (!isSuccess) return <div>Error</div>;

  return (
    <Suspense>
      {/* <TextGradient>{getExamName(exam)}</TextGradient> */}
      <p className='pdf-ready'>Zadania!</p>
      {exam && <span>Pobrano!</span>}
    </Suspense>
  );
}

When I open it with my dev environment it works fine – hook loads the data and page is displayed. However, when I open it with my backend (nestjs) and puppeeter like this:

    const browser = await puppeteer.launch({ executablePath: puppeteer.executablePath('chrome'), headless: false });
    const page = await browser.newPage();
    await page.goto(`http://localhost:3000/pdf/exam/${id}`, { waitUntil: 'networkidle0' });
    await page.waitForSelector('.pdf-ready');

    const filePath = path.resolve(process.cwd(), 'public', 'pdfs', `exam-${id}.pdf`);
    fs.mkdirSync(path.dirname(filePath), { recursive: true });

    const pdf = await page.pdf({
      path: filePath,
      printBackground: true,
      format: 'A4',
    });

    await browser.close();

then the page opens but the request to my server is not sent and after loading state, the error div appeared. What am I doing wrong? The page is public so its not related to authentication.

PhantomJS frozen stuck at blank terminal after trying use $.ajax

I have been porting my code to PhantomJs and have been having a hard time with using $.ajax in Jquery. I think it something with how my functions are defined but I am new to JavaScript. Here is my shortened code:

var page = require('webpage').create();
console.log('required webpage');

page.onConsoleMessage = function(msg) {
    console.log(msg);
};
console.log('added message event handler')

page.open('', function() {
    console.log('page.opened nnow in page context');
    page.render('opened.png');
    page.includeJs("https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function() {
        page.evaluate(function() {
            console.log('evaluating');

            function getMessages() {
                return new Promise((resolve, reject) => {
                    $.ajax({
                        url: 'https://www.example.com/myrequest.php',
                        type: 'POST',
                        data: {
                            mychar_id: 32,
                            offset: 0,
                            limit: 10
                        },
                        success: function(data) {
                            if (data.trim() === '') {
                                console.log("received null");
                                reject("Received null data");
                            } else {
                                resolve(data);
                            }
                        },
                        error: function(xhr, status, error) {
                            console.log('AJAX Error:', error);
                            reject(error);
                        }
                    });
                });
            }

            getMessages().then(data => {
                console.log(data);
            }).catch(error => {console.error(error);});

            console.log("extending jquery.");
            // JQuery stuff goes here.
            console.log('Final markup.')
            console.log(document.body.innerHTML);
        });
        page.render('done.png')
        console.log('exiting');
        phantom.exit();
      });
    });

However, when running this with phantomjs, all I see is a blank cursor and the only way to exit is with ^c. I have tried everything I can think of, moving functions, etc. but so far, no luck. I know my function works elsewhere. What can I do?

Fade in/out div within a div based on scroll position

I’m trying to fade in a div slowly as I scroll down to it (or up to it). The fade is supposed to be based on how much we scroll, so when it reaches the center, it would be fully visible.

My problem right now is that the scroll does not trigger at all. I’m loading jQuery and I can physically scroll inside the project-container div.

I tried implementing this code:

$('.project-container').scroll(function() {
  console.log('scrolling'); // This DOESN'T show up
});
.project-container {
  display: flex;
  flex-direction: column;
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;

  padding: 5%;
  gap: 30%;
  box-sizing: border-box;
  overflow-y: scroll;
}

.project {
  display: flex;
  height: auto;
  width: 100%;
  justify-content: space-between;

  opacity: 1;

  &.left {
    flex-direction: row;
  }

  &.right {
    flex-direction: row-reverse;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div class="project-container">
  <div class="project left">stuff</div>
  <div class="project right">stuff2</div>
</div>

Returning an array from server-side to client-side in Svelte 5

I am using Svelte5. When I send an array from +page.server.js to +page.svelte it always works server-side and the array is sent as expected. However when +page.svelte is running on the client side the array is always empty. Rather than ask a specific ‘what’s wrong with my code’ I want to ask a general question – how do you send an array back to +page.svelte.

My cut-down code is –

// +page.server.js 

export async function load({ url, cookies }) {
    return { Tom: await setUpTom() }
}

async function setUpTom() {
    let psTom = [];
    psTom.NoOfRecords = 34;
    psTom["L"] = [];
    psTom["L"].NoOfRecords = 4;
    return psTom;
}

// +page.svelte
...
let pcTom = data.Tom;
...

Below are my server-side logs (ps denotes action from +page.server, +p denotes action from +page.svelte) –

ps  
psTom => [  
    NoOfRecords: 34,  
    L: [ NoOfRecords: 4 ],  
    A: [ F: [ Records: [Array] ] ]  
]  

+p   
pcTom => [  
    NoOfRecords: 34,  
    L: [ NoOfRecords: 4 ],  
    A: [ F: [ Records: [Array] ] ]  
] 

They are the same. But this is the server-side log, so when +page.svelte runs server-side it works fine.

When running client-side the client log has pcTom as empty –

+p      
pcTom =>   
    Array []  
        length: 0  

I have tried lots of combinations of sending my array back (including using JSON below) and in each case it works fine server-side (psTom and pcTom are correctly populated arrays) but when +page.svelte is running client-side the array is empty (pcTom = []).

async function setUpTom() {
...
     return JSON.stringify(psTom);
}

then
let pcTom = JSON.parse(data.Tom);

What am I missing?

Session variable not updating during loop in PHP?

I’m facing a problem with my app. It’s in a JS-PHP environment. I’ve made a minimal reproduced example below.

script.js:

function postToHandler(){

    let xhr = new XMLHttpRequest();
    xhr.open("POST", "./apps/researcher.php");

    let form = new FormData();
    form.append('triggerLoop', "mockData");

    xhr.send(form);

    activateGlobalsListener();
}

function activateGlobalsListener(){
    
    setInterval(function(){
        let xhr_listen = new XMLHttpRequest();
        xhr_listen.open("POST", "./apps/researcher.php");

        let form = new FormData();
        form.append('listen', "mockData");
        xhr_listen.send(form);

        xhr_listen.onreadystatechange = function (){

            if(xhr_listen.readyState === XMLHttpRequest.DONE){
                console.log("RECEIVED LISTEN DATA");
                console.log(xhr_listen.response);   
            }
        }
    },1000);
}

And here is the php file

<?php

//SOURCE OF PROBLEM BELOW: When I uncomment the session_start line, the listening process stops working
//session_start();

$_SESSION['globalVar'] = "undefinedData";

if (!empty($_POST['triggerLoop'])) {

    for ($x = 0; $x < 10; $x++) {
        $_SESSION['globalVar'] = getResult();
        sleep(1);
    }
}

//------------------------------------------------------
//Listen
if (!empty($_POST['listen'])) {
    echo  $_SESSION['globalVar'];
}

function getResult()
{
    return rand(10, 100);
}

?>

My script.js file creates multiple XMLHttpRequests to the same researcher.php file.

The first request will initiate a loop within the PHP file. This loop will update a SESSION variable with a random int. There is a 1 second sleep call that also occurs during every iteration of that loop.

Then after the script.js has triggered this, my script.js file starts an interval (also every 1 second), where it will send a request to that same PHP file, attempting to read the value of that SESSION variable (which is supposed to get updated with a new value every 1 second).

But I find that the value of that SESSION variable is always the initial value with which it was defined.

So where am I wrong?

I have looked at similar questions on Stackexchange and some say that you should add a “session_start()” line at the top of the PHP file. But when I do that I’ve noticed a peculiar thing……the script.js is not getting the responses (within the setInterval) immediately. It seems to get those responses delayed….only after the entire PHP loop is finished. Why though? Why does starting a session have that effect?

Other similar questions also say that you should add a redirect call every time a SESSION variable is updated. Like

header("location:./Researcher.php");

To redirect the file to itself? But if I do that, won’t it break the current loop and all the ongoing processes?

Round to n or less decimal places

I’m trying to round the output of some calculations to 3 or less decimal places, so they can stored compactly in a comma-delimited text file. That is 2 should be stored as 2 not 2.000, 3.14 should be stored as 3.14 not 3.140, and so on.

The problem is, 0.001*Math.round(1000*value) works sometimes, but not all the time. When I check the file that was saved, it contains output like this:
0.165,1,1,0.17300000000000001,0,0,0.3,0.16,0.184,0.20800000000000002, which defeats the purpose of rounding for compactness in a text file.

What is wrong with this Promise.All code?

I have a page made up of multiple forms. Each form has it’s own javascript file with a validate method like so.

function validateForm(){
        return new Promise((resolve, reject) => {
            fetch(urls.validate)
                .then((r) => r.json())
                .then((json) => {
                    if (json.Success){
                        resolve("Complete!");
                    }else{
                        resolve(json.ErrorHtml);
                    }
                });
        });
    }

When the page loads, it loads up an array of the different javascript file methods to call like this.

var validationScripts = [];
validationScripts.push("eisForm.validateForm();");
validationScripts.push("background.validateForm();");

Finally, when the user gets to the last form the button needs to run all of the validation scripts.

async function runValidation(){
    const results = await Promise.all(validationScripts.map(script => script()));
    console.log(results);
}

This gives a TypeError: script is not a function error. I wasn’t sure if it might be because each validateForm is followed by () and then in the map method it uses () again. I tried removing them from the array’s push of each validateForm but I still get the same error.

I’m not sure how to make this work so that all of the Promises are awaited and the results const is a collection of all the resolved values.

how to convert Markdown lists to HTML in JavaScript [closed]

i really have no idea how to convert Markdown list to HTML and i don’t want to and can’t use any js package for it

i already implemented most of tags but im having really hard time with lists i manage to get unordered lists and ordered with ability to have sublists of ther own type in them but i need to have also unordered in ordered list and vice versa

like this:

  • List item
  • List item
    1. List item
    2. List item
    3. List item
  • List item

currently i have this:

unordered lists

{match: /((?:^s*[-*+] .*?$n)+)/gm, replace: (matched) => {
    let result = matched;
    result = result.replaceAll(/^[-+*] (.*?)$/gm, "<li>$1</li>").replaceAll(/^s/gm, "");
    function embed_lists(code){
        let output = code;
        if(output.match(/((?:^s*[-*+] .*?$n)+)/gm) !== null){
            output = output.replaceAll(/((?:^s*[-*+] .*?$n)+)/gm, (selected) => {
                let reuse = selected;
                reuse = reuse.replaceAll(/^[-+*] (.*?)$/gm, "<li>$1</li>").replaceAll(/^s/gm, "");
                reuse = embed_lists(reuse);
                return "<ul style='color:royalblue;'>"+reuse+"</ul>";
            });
        }else if(output.match(/((?:^s*d+. .*?$n)+)/gm) !== null){
            output = output.replaceAll(/((?:^s*d+. .*?$n)+)/gm, (selected) => {
                let reuse = selected;
                reuse = reuse.replaceAll(/^d+. (.*?)$/gm, "<li>$1</li>").replaceAll(/^s/gm, "");
                reuse = embed_lists(reuse);
                return "<ol style='color:olive;'>"+reuse+"</ol>";
            });
        }
        return output;
    }
    result = embed_lists(result);
    return "<ul>n"+result+"n</ul>";
}},

ordered lists

{match: /((?:^s*d+. .*?$n)+)/gm, replace: (matched) => {
    let result = matched;
    result = result.replaceAll(/^d+. (.*?)$/gm, "<li>$1</li>").replaceAll(/^s/gm, "");
    function embed_lists(code){
        let output = code;
        if(output.match(/((?:^s*d+. .*?$n)+)/gm) !== null){
            output = output.replaceAll(/((?:^s*d+. .*?$n)+)/gm, (selected) => {
                let reuse = selected;
                reuse = reuse.replaceAll(/^d+. (.*?)$/gm, "<li>$1</li>").replaceAll(/^s/gm, "");
                reuse = embed_lists(reuse);
                return "<ol style='color:greenyellow;'>"+reuse+"</ol>";
            });
        }else if(output.match(/((?:^s*[-*+] .*?$n)+)/gm) !== null){
            output = output.replaceAll(/((?:^s*[-*+] .*?$n)+)/gm, (selected) => {
                let reuse = selected;
                reuse = reuse.replaceAll(/^[-+*] (.*?)$/gm, "<li>$1</li>").replaceAll(/^s/gm, "");
                reuse = embed_lists(reuse);
                return "<ul style='color:skyblue;'>"+reuse+"</ul>";
            });
        }
        return output;
    }
    result = embed_lists(result);
    return "<ol>n"+result+"n</ol>";
}},

this code only lets me have ordered lists in ordered list and unordered lists in unordered list

theoretically it should work like this:

  1. find group of Markdown list tags with regex from match
  2. try to match list tag if its ordered or unordered
  3. get all the tags
  4. replace tags without space to HTML <li> tag
  5. delete one space from the rest of tags
  6. repeat until there is no more list tags
  7. return <li> tags wrapped with <ul> or <ol> tag
  8. return all tags wrapped in <ul> or <ol>

all tags are stored in big array of objects with how to find Markdown tag (match) and how to convert it to HTML (replace)

ES6 static class extends EventTarget

I wish to create a class which extends EventTarget, allowing addEventListener() and dispatchEvent() to be invoked on it.

Logically, my class wants to be a singleton; if a page accidentally instantiated more than one, its functionality would break. For this reason, I’ve implemented the entirety of this class’s logic as static fields and methods.

Unfortunately extends doesn’t seem to mesh neatly with static, so this doesn’t work:

class MyClass extends EventTarget {
   static dispatch(type) { MyClass.dispatchEvent(new Event(type)); }
}
MyClass.dispatch('hello');

Uncaught TypeError: MyClass.dispatchEvent is not a function

There must be something I can do with constructors and prototypes to bring EventTarget‘s methods directly into MyClass. Could someone enlighten me as to how I need to think through this? (Aside from the awkward hack of declaring a class static variable containing an EventTarget, and forwarding things to/from this.)

When I make a fetch request then take out the JSON, instead a promise is saved as a variable with the correct JSON in it

When I make a fetch request then take out the JSON, instead a promise is saved as a variable with the correct JSON in it. I can not figure out how to pull the data from the promise in the variable in order to actually use the data.

When I test the URL using postman or just putting it into my browser gives back JSON so this formatting I believe to be an issue on my codes end.

The function for the call is as follows:

  var responseData = await fetch('https://api.sampleapis.com/wines/reds')
  .then((response) => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    var jsonData = response.json();
    console.log(jsonData);
    return jsonData
  })
}

The logged json in console looks like this:

Promise {<pending>}
[[Prototype]]
: 
Promise
[[PromiseState]]
: 
"fulfilled"
[[PromiseResult]]
: 
Array(718)

The Array(718) contains the desired payload looking like this:

[0 … 99]
[100 … 199]
[200 … 299]
[300 … 399]
[400 … 499]
[500 … 599]
[600 … 699]
[700 … 717]
length
: 
718

The interiors of these 8 arrays looks like this (the JSON is finally present):

[0 … 99]
0: 
{winery: 'Maselva', wine: 'Emporda 2012', rating: {…}, location: 'Spainn·nEmpordà', image: 'https://images.vivino.com/thumbs/ApnIiXjcT5Kc33OHgNb9dA_375x500.jpg', …}
1: 
{winery: 'Ernesto Ruffo', wine: 'Amarone della Valpolicella Riserva N.V.', rating: {…}, location: 'Italyn·nAmarone della Valpolicella', image: 'https://images.vivino.com/thumbs/nC9V6L2mQQSq0s-wZLcaxw_pb_x300.png', …}
2: 
{winery: 'Cartuxa', wine: 'Pêra-Manca Tinto 1990', rating: {…}, location: 'Portugaln·nAlentejo', image: 'https://images.vivino.com/thumbs/L33jsYUuTMWTMy3KoqQyXg_pb_x300.png', …}
3: 
{winery: 'Schrader', wine: 'Cabernet Sauvignon RBS Beckstoffer To Kalon Vineyard 2015', rating: {…}, location: 'United Statesn·nOakville', image: 'https://images.vivino.com/thumbs/GpcSXs2ERS6niDxoAsvESA_pb_x300.png', …}
4: 
{winery: 'Hundred Acre', wine: 'Wraith Cabernet Sauvignon 2013', rating: {…}, location: 'United Statesn·nNapa Valley', image: 'https://images.vivino.com/thumbs/PBhGMcRNQ7aVnVNr7VgnWA_pb_x300.png', …}
5: 
{winery: 'Sine Qua Non', wine: 'Ratsel Syrah N.V.', rating: {…}, location: 'United Statesn·nCalifornia', image: 'https://images.vivino.com/thumbs/ZzMKzqFqRO-6oI3ys3gGgQ_pb_x300.png', …}
6: 
{winery: 'Del Dotto', wine: 'The Beast Cabernet Sauvignon 2012', rating: {…}, location: 'United Statesn·nRutherford', image: 'https://images.vivino.com/thumbs/easjTPIcS-mCQ99XoYOMgQ_pb_x300.png', …}
7: 
{winery: 'Darioush', wine: 'Darius II Cabernet Sauvignon 2016', rating: {…}, location: 'United Statesn·nNapa Valley', image: 'https://images.vivino.com/thumbs/U19RXtSdRMmoAesl2CBygA_pb_x300.png', …}
8: 
{winery: 'Garbole', wine: 'Hurlo 2009', rating: {…}, location: 'Italyn·nVeneto', image: 'https://images.vivino.com/thumbs/f_G1SS0eT_C6hZGGwdEZqA_pb_x300.png', …}
9: 
{winery: 'Scarecrow', wine: 'Cabernet Sauvignon 2016', rating: {…}, location: 'United Statesn·nRutherford', image: 'https://images.vivino.com/thumbs/pU7uFKR-TAKAOQaf3Hpn2A_pb_x300.png', …}

Loop through and access rows of a lookup table

I’m using Blogger, and after 20 years and 10K posts, I have exported all posts and migrated all content to a new CMS and a new domain. By using jQuery in the Blogger HTML template, I have set up links in all Blogger posts to the same post at the new domain, i.e. with an HTML link “Click to go to the new site”.

And that works for many of the Blogger > New site post links, because the post name part of the slug is the same after the migration, i.e., old: https://example.blogspot.com/a-post.html and new: https://mynewdomain.com/a-post.html so displaying a redirect is easy. I use jQuery in Blogger HTML template to replace example.blogspot.com with mynewdomain.com to form a redirect link.

But due to the method of importing Blogger content into the new CMS, I have hundreds of posts where the destination URL is different, e.g. https://example.blogspot.com/another-post.html needs to link to https://mynewdomain.com/another-post-2.html

I thought of a way to create new links at Blogger with jQuery: use a two value “A:B” structure lookup table to store the new and old URLs and to loop through and show a link to the post at the new domain, like this:

var lookupTable = {
"https://example.blogspot.com/a-post.html";"https://mynewdomain.com/a-post-2.html",
"https://example.blogspot.com/another-post.html";"https://mynewdomain.com/another-post-2.html",
// etc.....
};

But how do I loop through and conditionally call the mynewdomain URLs in the lookup table? An if-else loop? A for-each loop?

This is my pseudo code:

  • When jQuery is On Document ready, get the window URL of the single post, ThePostURL.

  • Loop through the lookupTable and determine if the ThePostURL is in the first position in any row of the table, i.e. “A” of the “A:B” structure.

  • If ThePostURL does not exist, exit and simply show a link with the domain changed.

  • If the ThePostURL does exist in the table in position “A”, use jQuery to replace the “B” position URL in HTML to form a link to the “B” URL.

Which of the 10,000 properties are in a drawn polygon

I have Javascript code that can detect the coordinates of a polygon that is drawn on Google map. I also have 10,000 property addresses. What is the fastest way to find which of the 10,000 properties are within the bounds of the polygon? I could loop through 10,000 calls to “google.maps.geometry.poly.containsLocation(coordinates, polygon)” but I am afraid that would take a long time. I need to be able to process 10,000 coordinates in a timely manner. The polygon will change. The user will be drawing different polygons on the Google map on any given day. Can I pass an array to “containsLocation()”?

I can call the “geocoder.geocode({ address }, (results, status)” function and get the coordinates of each address and then store the coordinates in an array.

Thank you for your time and expertise. Robert

My code:

coordinates = { lat: 34.075704, lng: -118.3967108 };  

var mapOptions = {
    center: new google.maps.LatLng(coordinates),
    zoom: zoom,
    mapId: "xxxx"
};

map = new Map(document.getElementById("google_map_desktop"), mapOptions);

drawingManager = new google.maps.drawing.DrawingManager({
    drawingControl: true,
    drawingControlOptions: {
        position: google.maps.ControlPosition.TOP_CENTER,
        drawingModes: ['polygon', 'rectangle']
    },
    polygonOptions: {
        editable: true,
    }
});

drawingManager.setMap(map);

google.maps.event.addListener(drawingManager, 'polygoncomplete', (polygon) => {
    var coordinatesArray = polygon.getPath().getArray(); 

    var inside_of_polygon;

    // Loop for each property address   (10,000 times)
    for (each address) {
        inside_of_polygon = google.maps.geometry.poly.containsLocation(coordinates, polygon);
    
        If inside_of_polygon == true) {
            // add these coordinates to the in_polygon array
        }
    }
}); 

Property Addresses (10,000)
2081 Sunset Plaza Drive, Los Angeles, CA, 90069
3156 Lake Hollywood Drive, Los Angeles, CA, 90068
80 Grace Terrace, Pasadena, CA, 91105