React state not updating Framer Motion variant

I am trying to simply pass a boolean React state into Framer Motion’s variants function. The state doesn’t seem to update in the variants. I’m confused. Any suggestions would be appreciated. I can log the state of beatFast and it is correct. However the value is not being updated in Framer Motion’s variants.

import React from "react";
import useMousePosition from "./useMousePosition";

interface HeartIconProps {
  tapped?: boolean;
  x?: MotionValue<number>;
  y?: MotionValue<number>;
}

export function HeartIcon({ tapped, x, y }: HeartIconProps) {
  const [beatFast, setBeatFast] = React.useState<boolean>(false);
  const [beating, setBeating] = React.useState<boolean>(true);

  React.useEffect(() => {
    if (!x || !y) {
      return;
    }
    console.log(x?.get(), y?.get());
  });

  setTimeout(() => {
    setBeatFast(true);
  }, 3000);

  const heartVariants = (beatFast: boolean) => ({
    resting: {
      scale: [1, 1, 1],
      opacity: 1,
      transition: {
        repeat: 0,
        duration: 0
      }
    },
    beating: {
      scale: [1, 1.2, 1],
      opacity: 0.9,
      transition: {
        repeat: Infinity,
        duration: beatFast ? 0.4 : 3
      }
    },
    tapped: {
      scale: [3, 1],
      opacity: [0.2, 1],
      transition: {
        type: "spring",
        bounce: 0.5,
        mass: 1
        // times: [0.2, 0.6, 1]
      }
    }
  });

  return (
    <div ref={svgRef}>
      <motion.svg
        viewBox="0 0 36 36"
        fill="none"
        xmlns="http://www.w3.org/2000/svg"
        width="100%"
        animate={tapped ? "tapped" : beating ? "beating" : "resting"}
        variants={heartVariants(beatFast)}
      >
        <path
          d="M35.885 11.833c0-5.45-4.418-9.868-9.867-9.868-3.308 0-6.227 1.633-8.018 4.129-1.791-2.496-4.71-4.129-8.017-4.129-5.45 0-9.868 4.417-9.868 9.868 0 .772.098 1.52.266 2.241C1.751 22.587 11.216 31.568 18 34.034c6.783-2.466 16.249-11.447 17.617-19.959.17-.721.268-1.469.268-2.242z"
          fill={`red`}
        />
      </motion.svg>
    </div>
  );
}

Code sandbox

Issue with Copying and Pasting Files Using Google Drive API

I’m encountering an issue when trying to use the Google Drive API to copy and paste a file into a specific folder. The copy operation is successful; however, the copied file is pasted back into the source folder instead of being moved to the specified destination folder.

Here is the code snippet I’m using:

        // Folder ID you want to copy.
        const folderId = '1g9rSD-file_copied';

        // New folder ID that will be the destination of the copy.
        const parentFolderId = '1xu6TIz_my_folder_destination';       
        const accessToken = "my_access_token_here";

        const requestBody = {
            parents: [parentFolderId],
            supportsAllDrives: true,
        };

        const queryString = new URLSearchParams(requestBody).toString();
        const copyUrl = `https://www.googleapis.com/drive/v3/files/${folderId}/copy?${queryString}`;

        fetch(copyUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${accessToken}`,
            }
        })
        .then(response => response.json())
        .then(data => {

            console.log('Cópia concluída:', data);
        })
        .catch(error => {
            console.error('Erro na requisição:', error);
        });

I expected the file to be copied to the folder specified in parentFolderId, but instead, it’s pasted into the source folder.

Has anyone faced a similar issue or has any suggestions on what might be causing this unexpected behavior?

Appreciate any help in advance!

Javascript – Fill area under a spline in an area chart

I am trying to fill in the area between the red line(solar) and yellow bar(nuclear) in the graph below. I cannot for the life of me figure it out and am out of ideas.I’d like to fill it in red. Find my code below the image.
I would also like to be able to have the red spline above nuclear without having to add the value of the grey, blue and yellow bar together and adding it to the solar value but could find no other way.
Thanks!

enter image description here

var TotalNonGreenPower = 200 + 300 + 500;
    var energyData = [
        { time: '12:00am', hydro: 200, solar: TotalNonGreenPower + 0 },
        { time: '2:00am', hydro: 200, solar: TotalNonGreenPower + 0 },
        { time: '4:00am', hydro: 200, solar: TotalNonGreenPower + 0 },
        { time: '6:00am', hydro: 200, solar: TotalNonGreenPower + 100 },
        { time: '8:00am', hydro: 200, solar: TotalNonGreenPower + 100 },
        { time: '10:00am', hydro: 200, solar: TotalNonGreenPower + 100 },
        { time: '12:00pm', hydro: 200, solar: TotalNonGreenPower + 200 },
        { time: '2:00pm', hydro: 200, solar: TotalNonGreenPower + 200 },
        { time: '4:00pm', hydro: 200, solar: TotalNonGreenPower + 100 },
        { time: '6:00pm', hydro: 200, solar: TotalNonGreenPower + 100 },
        { time: '8:00pm', hydro: 200, solar: TotalNonGreenPower + 0 },
        { time: '10:00pm', hydro: 200, solar: TotalNonGreenPower + 0 }
    ];

    Highcharts.chart('container', {
        chart: {
            type: 'area'
        },
        title: {
            text: 'Power Consumption'
        },
        xAxis: {
            categories: energyData.map(point => point.time),
            title: {
                text: 'Time'
            }
        },
        yAxis: {
            title: {
                text: 'MegaWatts'
            }
        },
        plotOptions: {
            area: {
                stacking: 'normal',
                /*fillOpacity: 0.5*/
            },
            series: {
                marker: {
                    enabled: false
                }
            }
        },
        series: [
            {
                name: 'Hydro',
                data: energyData.map(point => [point.time, point.hydro]),
                color: 'blue',
                type: 'area',
                index: 2
            },
            {
                name: 'Nuclear',
                data: energyData.map(point => [point.time, 300]),
                color: 'yellow',
                type: 'area',
                index: 1
            },
            {
                name: 'Gas',
                data: energyData.map(point => [point.time, 500]),
                color: 'gray',
                type: 'area',
                index: 3
            },
            {
                name: 'Solar',
                data: energyData.map(point => [point.time, point.solar]),
                color: 'red',
                type: 'spline',
                index: 0
            },
            {
                name: 'Curve',
                data: [
                    [energyData[0].time, 500],
                    ['10:00am', 1500],
                    ['8:00pm', 2000],
                    ['10:00pm', 500]
                ],
                color: 'rgba(0, 0, 0, 0.5)',
                type: 'spline'
            }
        ]
    });

Trying to add rows using JS

I am trying to add row with js but its doesn’t work.

$('#addrow').click(function() {
  var length = $('.sl').length;
  var i = parseInt(length) + parseInt(1);
  var newrow = $('#next').append('<label for="Age">Sl No:</label>...<input type="button" class="btnRemove btn-danger" value="Remove"/></div><br>');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div id="next"></div>

<button type="button" name="addrow" id="addrow" class="btn btn-success pull-right">Add New Row</button>

How to create a beautiful date selection in a form? [closed]

Good evening, while designing a form I stopped at one point and still can not figure out how to implement it, I will be grateful for any help

There is a form that I am designing, and there is a field for selecting the date

screenshot in figma

I have attached a screenshot from figma. How can I create such an input so that when I click on it, a calendar appears and the date is displayed that way?

Thanks for any help again!

I’ve already tried searching for calendar plugins and googling this problem, but I haven’t found it.

What I expect from such an input is that when clicked, the calendar is shown, the user selects a date, and the date is displayed as on the design

Cannot find proper value in mapped array

here is my code:

               <tbody>
                  @foreach ($meals as $keys=>$meal)
                      <tr>
                        <td>{{$keys+1}}</td>
                        <td>{{$meal->date}}</td>
                        @php
                          $detailsmeals= json_decode($meal->mealdetails);                                            
                        @endphp
                        @for ($i = 0; $i < count($detailsmeals->breakfasts); $i++)
                            <td class="breakfast text-center table-primary">{{$detailsmeals->breakfasts[$i]}}</td>
                            <td class="lunch text-center table-info">{{$detailsmeals->lunchs[$i]}}</td>
                            <td class="dinner text-center table-secondary">{{$detailsmeals->dinners[$i]}}</td>                       
                        @endfor              
                      </tr>
                      
                  @endforeach
                  <script>
                    const tbody = document.querySelector('table tbody');
                    const outputArray = () => Array.from(tbody.querySelectorAll('tr')).map(tr => ({
                              break: tr.querySelector('.breakfast').innerText,
                              lunch: tr.querySelector('.lunch').innerText,
                              dinner: tr.querySelector('.dinner').innerText
                          }));
                    console.log(outputArray());
              </script>
                </tbody>

and my output is: here only first break, lunch, dinner array of each row, how can I find all break, lunch, dinner array value of each row, please help me.

Changes to HTML not happening

<script>
   function myFunction(x,y) {
       const a = document.getElementById(x);
       if (a !== null) {
         console.log('a: ',a);
       }
       var e = a.querySelector('.'+y);
       if (e !== null) {
         console.log('e:',e);
       }
       if (e) {
           // Creates new div
           var d = document.createElement('div');
           d.className = y;
           d.style.visibility = 'hidden';
           // Adjust the visibility
           d.innerHTML = e.innerHTML;
           // Insert
           e.parentNode.insertBefore(d, e);
           e.parentNode.removeChild(e);
           console.log('d: ',d)
           return d
       } else {
           console.error('Child div not found');
       }
   }
     //
     document.addEventListener('DOMContentLoaded', function() {
   
       myFunction('block-2','summary');
     });
   </script>
</head>
<body>

 <!-- The target div with id "myDiv" -->
 <div id="block-3">
   <div class="summary">
     <p class="block">This is a block.</p>
       </div>
 </div>
 <div id="block-2">
   <div class="summary">
     <p>Something to think about.</p>
   </div>
 </div>
 <div id="block-1">
   <div class="summary">
      <p>This is the last block.</p>
   </div>
 </div>

</body>
</html>

I am expecting to hide the child “.summary” tag in a specific parent “#block-2” tag. This code works.

Yes, you could do this as well … for the function.

function myFunction(x,y) {
var a = document.getElementById(x);
var b = a.querySelector('.'+y);
return b.style.visibility = "hidden";
};

The going concern I have is the code doesn’t change the html in a hosted environment. I am using squarespace.com

three.js rotate around line and toward camera

I’m trying to set static rotation to box – it should rotate around the line (or to be more precise line should be the rotation axis) but it should be toward the camera. If you still get the purpose - just imagine holding a lolly pop and rotating stick that it would look on the camera.

I’m almost achieving the expected result but it is rotating around itself axis as well - like in the example with lolly pop the the sweet part is rotating around the point it is attached to the stick which is not the goal

enter image description here

Here is the code sandbox for example: https://codesandbox.io/s/rotation-around-line-forked-smyqxx?file=/src/App.js

const FirstPoint = new THREE.Vector3(-0.02, 0.05, 0)
const SecondPoint = new THREE.Vector3(0.09, 0.01, -0.06)

    const box = meshRef.current

    box.position.copy(FirstPoint)

    var lineDirection = new THREE.Vector3().subVectors(SecondPoint, FirstPoint).normalize()

    var cameraDirection = new THREE.Vector3().subVectors(camera.position, FirstPoint).normalize()

    var rotationAxis = new THREE.Vector3().crossVectors(cameraDirection, lineDirection).normalize()

    box.quaternion.setFromUnitVectors(new THREE.Vector3(0, 0, 1), rotationAxis)

    var q = new THREE.Quaternion().setFromAxisAngle(lineDirection, Math.PI / 2)
    box.quaternion.multiplyQuaternions(q, box.quaternion)

Problems in import external native javascript file in vue3?

I want use the QRCodeJS library in Vue3 fllowing the tutorial.

I tried the NPM package but it didn’t work. So I tried use pure JS library, including package from a script tag using a CDN but I didn’t reach the QRCode object of the package. It gave me error that it is not defined.

Can I include javascript native libraries in Vue, from publicindex.html in Vue3? Is there a way to do this? Can you give examples? It doesn’t have to be with this specific pacakge.

Thanks for all help.

First

Include package in publicindex.html

<script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>

Second

Use QRCode object, in component, within script tag i created QRCode object, as follow:

var qrcode = new QRCode("qrcode", "https://www.geeksforgeeks.org");

Result

130:19  error  'QRCode' is not defined  no-undef

Converting xlsx to JSON and storing in a specific format

I am working on a project and I am stuck at one point:

so I have xlsx sheet with some data:
enter image description here

and when I convert to JSON like this :

if (selectedFile) {
const formData = new FormData();
formData.append("file", selectedFile);
const workbook = XLSX.read(await selectedFile.arrayBuffer(), {
type: "array",
      });
const firstSheetName = workbook.SheetNames[0];
const worksheet = workbook.Sheets[firstSheetName];
const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
}

and console.log(jsonData):

the result is it take each row separately and make object of each row:

enter image description here

but I want this jsonData to be stored in a different way

 `if (selectedFile) {
const formData = new FormData();
formData.append("file", selectedFile);
const workbook = XLSX.read(await selectedFile.arrayBuffer(), {
type: "array",
      });
const firstSheetName = workbook.SheetNames[0];
const worksheet = workbook.Sheets[firstSheetName];
const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

if (jsonData.length > 0) {
const headers = data[0];

Create a dictionary to store column names and their values as arrays
const columnDict: { [key: string]: string[] } = {};

headers.forEach((header: string) => {
columnDict[header] = data
            .slice(1)
            .map((row: any) => row[headers.indexOf(header)]);
        });

Update state with the column data
setColumnData(columnDict);
      }
}`

I have tried like this but now :

I am expecting it like :

> ```
> Chemicals: ["Silicon","2nd value", "3rd value",....]
> Diameter: [1,"2nd value", "3rd value",....]
> Effect endpoint: ["Feret Minimal","2nd value", "3rd value",....]
> Effect endpoint type: ["Median","2nd value", "3rd value",....]
> Endpoint: ["Nano","2nd value", "3rd value",....]
> Endpoint Method: ["Invest1","2nd value", "3rd value",....]
> Endpoint category: ["Solid","2nd value", "3rd value",....]
> Material: ["Light","2nd value", "3rd value",....]
> Medium: ["CORE","2nd value", "3rd value",....]
> Name: ["1.1_SiC@TiO2_60","2nd value", "3rd value",....]
> Percentage: ["0.22","2nd value", "3rd value",....]
> Project: ["Sunshine","2nd value", "3rd value",....]
> ```

all the values would be in a array according to the corresponding headers.

Thank you so much in advance

How to contruct an Authorization Header for Azure Storage on Node-red without crypto library?

I’m trying to connect to azure storage using their API on node-red.
Since my node red couldn’t NPM install anything on it, I try other way round to create the HMAC and sign it. After I construct the header and content required, it showed:

<?xml version="1.0" encoding="utf-8"?><Error><Code>AuthenticationFailed</Code><Message>Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.
RequestId:f280ad0a-501e-0011-5e83-197426000000
Time:2023-11-17T18:22:46.2298708Z</Message><AuthenticationErrorDetail>The MAC signature found in the HTTP request 'MzZlM2M0ZWQzYzdiYjM2NjVhNTQ4NzA0MDhhMjk2NzdkMjdiNjM3YjhlYzM5N2UzYTkxZmIzODkwZjAxNDNiOQ==' is not the same as any computed signature. Server used following string to sign: 'GET
x-ms-date:Fri, 17 Nov 2023 18:22:46 GMT
x-ms-version:2020-04-08
/litmusdev133/litmus
comp:list
restype:container'.</AuthenticationErrorDetail></Error>

My Overall Flow on Node-red:
Node-red Overall Flow

Function 1 :

function createBlobServiceSignature(storageAccount, storageKey, method, contentLength, contentType, date, resource) {
        // Parts of the string to sign
    const parts = [
        method.toUpperCase(),
        "",  // Content-Encoding
        "",  // Content-Language
        contentLength || "",  // Content-Length (empty string for zero)
        "",  // Content-MD5
        contentType || "",
        "",  // Date
        "",  // If-Modified-Since 
        "",  // If-Match
        "",  // If-None-Match
        "",  // If-Unmodified-Since
        "",  // Range
        canonicalizeHeaders({ "x-ms-date": date }),  // Canonicalized headers
        msVersion,
        resource,  // Canonicalized resource
        "comp:list",
        "restype:container"
    ];

    // Create the string to sign
    const stringToSign = parts.join('n');
    msg.string = stringToSign;

    // Decode the storage key
    const key = Buffer.from(storageKey, 'base64');
    msg.secrectkey = key;

    return stringToSign
    
}

function canonicalizeHeaders(headers) {
    // Sort headers and format them
    return Object.keys(headers)
        .sort()
        .map(name => `${name.toLowerCase().trim()}:${headers[name].trim()}`)
        .join('n');
}

// Example usage
const storageAccount = 'litmusdev133';
const storageKey = 'Example';
const method = 'GET';
const contentType = '';
const date = new Date().toUTCString();
const resource = '/litmusdev133/'
const msVersion = "x-ms-version:2020-04-08"

const authorizationHeader = createBlobServiceSignature(storageAccount, storageKey, method, '', contentType, date, resource);

// Setting the output message
msg.payload = authorizationHeader;
msg.secrectkey = storageKey;
msg.payload = Buffer.from(msg.payload).toString('utf8');

return msg;

Function 2:

// Example usage
const storageAccount = 'litmusdev133';
const storageKey = 'Example';
const method = 'GET';
const contentType = '';
const date = new Date().toUTCString();
const resource = '/litmusdev133/'
                            
const signature = msg.payload

msg.payload = 'SharedKey ' + storageAccount + ':' + signature;

return msg

Function 3 :

// Get the current date and time in UTC
var now = new Date();

// Convert UTC to GMT+8
var gmt8 = new Date(now.getTime())

// Convert to a string in a standard format
var gmt8String = gmt8.toUTCString();

authorization = msg.payload

msg.headers = {
    "x-ms-date" : gmt8String,
    "x-ms-version" :  "2020-04-08",
    "Authorization" : authorization
};

msg.reqheader = msg.headers;

return msg;

HMAC Configuration:
HMAC

Base64 Configuration:
Base 64

HTTP Configuration:
HTTP

I can assure that my secret key and container is correct.
I tried on python and it worked, so I try to replicate the steps to the node red flow but I get authentication failed instead.

Here is the python code that i reference to create the node-red flow:

import requests
import hmac
import hashlib
import base64
from datetime import datetime, timezone

account_name = 'litmusdev133'
account_key = 'Example'
container_name = 'litmus'

url = f'https://{account_name}.blob.core.windows.net/{container_name}?restype=container&comp=list'
current_time = datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')
string_to_sign = f"GETnnnnnnnnnnnnx-ms-date:{current_time}nx-ms-version:2020-08-04n/{account_name}/{container_name}ncomp:listnrestype:container"
signature = base64.b64encode(hmac.new(base64.b64decode(account_key), string_to_sign.encode('utf-8'), hashlib.sha256).digest()).decode()
authorization_header = f"SharedKey {account_name}:{signature}"
headers = {
    'x-ms-date': current_time,
    'x-ms-version': '2020-08-04',
    'Authorization': authorization_header
}

response = requests.get(url, headers=headers)
print(response.text)

Any guidance would be much appreciate, Thanks

Collisions Three.js Octree

Am Tryning to make that my character dont go inside my glb model of map, I saw this :
https://threejs.org/examples/#games_fps
and tried using the octree but getting an error if someone can help me setup collisions and if I need to setup something in my map file.

My map loader code :

const worldOctree = new Octree();
export function setupLevel(scene) {
  const loader = new GLTFLoader();
  loader.load(
  "../../models/level.glb",
  (gltf) => {
    scene.add(gltf.scene);
    worldOctree.fromGraphNode(gltf.scene);
    gltf.scene.position.y += 0.1;

    const helper = new OctreeHelper(worldOctree);
    helper.visible = true;
    scene.add(helper);
   },
   (xhr) => {
     console.log((xhr.loaded / xhr.total) * 100 + "% loaded");
   },
   (error) => {
    console.error(error);
   }
 );
 return worldOctree;
}

Reactjs not showing local images

I am learning React and recently ran into an issue. I’m saving a .jpg image locally in a public library see screenshot #1 and utilizing a relative path src='../images/book-2.jpg' to import the image into the locally hosted app (see full code below). The app is loading everything but the image see screenshot #2. I am not using webpack as some of the online threads discuss, and I have copied the settings listed in the following github folder vs-code-setup-2022. I read through similar previous questions related to this issue (examples: Local images are not showing on React App, React won’t load local images, and React won’t load local images.

import React from 'react'
import ReactDOM from 'react-dom/client'
import './index.css'

const BookList = () => {
  return (
    <section className='booklist'>
      <Book />
      <Book />
      <Book />
      <Book />
    </section>
  )
}

const Book = () => {
  return (
    <article className='book'>
      <Image />
      <Title />
      <Author />
    </article>
  )
}

const Image = () => (
  <img
    src='../images/book-2.jpg'
    alt='Friends, Lovers, and the Big Terrible Thing'
  />
)
const Title = () => <h2>Friends, Lovers, and the Big Terrible Thing</h2>
const Author = () => {
  return <h4>Matthew Perry</h4>
}

const root = ReactDOM.createRoot(document.getElementById('root'))

root.render(<BookList />)

I tried the following solutions based on what I gathered from these and others fora without favorable results:

  1. Using an absolute path src='/images/book-2.jpg';, but this didn’t work.
  2. Checking whether the web server is not serving the images, but I’m not seeing any 404 errors in the browser console.
  3. Creating an import statement import picture from "../images/book-2.jpg"; <img src={picture}/>, but I received an error – ERROR in ./src/index.js 7:0-43
    Module not found: Error: You attempted to import ../images/book-2.jpg which falls outside of the project src/ directory. Relative imports outside of src/ are not supported.
    You can either move it inside src/, or add a symlink to it from project’s node_modules/.
  4. Using {require()} didn’t help either.
  5. Using two dots to import images in the like fashion src='../images/book-2.jpg', which didn’t work for me.

I’d appreciate any helpful hints to move past this.

Google maps javascript/jquery api not loading map asp.net

I have searched everywhere on stack overflow for a solution for this while there are similar issues and questions out there none of them address my specific issue.

For months this google maps page i have was working but suddenly started just displaying a blank map.

Here is what the code previously looked like that was working up until today

@using something.ViewModel
@model IGoogleMapsCapable

<link href="@Html.ContentVersioned("/Content/GoogleMapStyle.css")" rel="stylesheet" type="text/css" />
<script src="@Html.ContentVersioned("/Scripts/google-maps.js")"></script>


@Html.HiddenFor(x => x.GoogleMaps.OriginalLat)
@Html.HiddenFor(x => x.GoogleMaps.OriginalLng)
@Html.HiddenFor(x => x.GoogleMaps.NewLat)
@Html.HiddenFor(x => x.GoogleMaps.NewLng)


<div class="alert alert-danger" role="alert">
    <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
    <span class="sr-only">The current Latitude/Longitude is not considered accurate enough to bind the policy. Please enter a new Latitude/Longitude here</span>
    <p>The current Latitude/Longitude is not considered accurate enough to bind the policy. Please enter a new Latitude/Longitude <a class="mimic-hyperlink-text" href="#modalGoogleMap" data-toggle="modal" data-target="#modalGoogleMap">here</a></p>
</div>

<div class="modal fade in" id="modalGoogleMap" tabindex="-1" role="dialog" aria-labelledby="modalGoogleMap" data-backdrop="static" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" id="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <p class="modal-title" id="red-txt">Geolocation did not return as rooftop. Please drag and drop red pin on home location</p>
            </div>
            <div class="modal-body row-fluid">
                <div class="well">
                    <div id="map"></div>
                </div>
                <div class="well">
                    <div id="lngLat">
                        <input type="text" class="lngText" id="lngText" aria-label="Longitude"/>
                        <input type="text" class="latText" id="latText" aria-label="Latitude"/>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" name="modalGoogleMapClose" id="modalGoogleMapClose" class="btn btn-primary">Update</button>
                <button type="button" name="modalGoogleMapCancel" id="modalGoogleMapCancel" class="btn" data-dismiss="modal">Cancel</button>
            </div>
        </div>
    </div>
</div>

and the jquery

(function ($) {
    $(document).ready(function () {
        let map;
        let marker;

        if (true)
        {
            $('#modalGoogleMap').modal('show');
        }
        
        originalLatLng = {
            lat: parseFloat($('#GoogleMaps_OriginalLat').val()),
            lng: parseFloat($('#GoogleMaps_OriginalLng').val())
        };

        newLatLng = {
            lat: parseFloat($('#GoogleMaps_NewLat').val()),
            lng: parseFloat($('#GoogleMaps_NewLng').val())
        };


        function markerUpdate(map) {
            marker.setMap(null);
            debugger
            newLatLng.lat = parseFloat(document.getElementById("latText").value);
            newLatLng.lng = parseFloat(document.getElementById("lngText").value);
            

            marker = new google.maps.Marker({
                position: newLatLng,
                map,
                title: 'Map Pin Updated: Manual Input',
                draggable: true
            });

            marker.setMap(map);

        }

        function addMarkerListener(map, marker) {
            map = new google.maps.event.addListener(marker, 'dragend', function (evt) {
                newLatLng.lat = evt.latLng.lat().toFixed(6);
                newLatLng.lng = evt.latLng.lng().toFixed(6);

                $('#lngText').val(newLatLng.lng);
                $('#latText').val(newLatLng.lat);
            });

        }

        function initMap() {
            map = new google.maps.Map(document.getElementById("map"), {
                center: originalLatLng,
                zoom: 18
            });

            marker = new google.maps.Marker({
                position: originalLatLng,
                map,
                title: 'Rooftop of Home to be Insured',
                draggable: true
            });
            addMarkerListener(map, marker);
            debugger

            $('#lngText').val(originalLatLng.lng)
            $('#latText').val(originalLatLng.lat)
            document.getElementById("latText").oninput = function () { markerUpdate(map) };
            document.getElementById("lngText").oninput = function () { markerUpdate(map) };


        }

        
        $('#modalGoogleMapClose').click(function () {

            GetNewLocation();
        });

        $('#modalGoogleMapCancel').click(function () {
            initMap();
        })

        $('#close').click(function () {
            initMap();
        })


        $("#GeoInformation").validate({
            submitHandler: function (form) {
                let isSuccess = GetNewLocation();
                if (isSuccess) {
                    form.submit();
                }
            },
            errorPlacement: function (error, element) {
                error.insertBefore(element);
            },
            onkeyup: false,
            onclick: false
        });

        // Create the script tag, set the appropriate attributes
        var script = document.createElement('script');
        script.src = 'https://maps.googleapis.com/maps/api/js?v=quarterly&key=MyActualKeyHere&callback=initMap';
        script.async = true;

        // Attach your callback function to the `window` object
        window.initMap = function () {
            // JS API is loaded and available
            initMap();
        };

        // Append the 'script' element to 'head'
        document.head.appendChild(script);

    }); // End document ready
})(this.jQuery);

Please any help would be appreciated I have been breaking my head trying to figure this one out

Looking through google maps api js documentation ive tried their suggested changes https://developers.google.com/maps/documentation/javascript/load-maps-js-api

(function ($) {
    $(document).ready(function () {
        let gmap;
        let marker;

        if (true) {
            $('#modalGoogleMap').modal('show');
        }

        let originalLatLng = {
            lat: parseFloat($('#GoogleMaps_OriginalLat').val()),
            lng: parseFloat($('#GoogleMaps_OriginalLng').val())
        };

        let newLatLng = {
            lat: parseFloat($('#GoogleMaps_NewLat').val()),
            lng: parseFloat($('#GoogleMaps_NewLng').val())
        };


        function markerUpdate(gmap) {
            marker.setMap(null);
            newLatLng.lat = parseFloat(document.getElementById("latText").value);
            newLatLng.lng = parseFloat(document.getElementById("lngText").value);

            marker = new google.maps.Marker({
                gmap,
                position: newLatLng,
                title: 'Map Pin Updated: Manual Input',
                draggable: true
            });

            marker.setMap(gmap);
        }

        function addMarkerListener(gmap, marker) {
            gmap = new google.maps.event.addListener(marker, 'dragend', function (evt) {
                newLatLng.lat = evt.latLng.lat().toFixed(6);
                newLatLng.lng = evt.latLng.lng().toFixed(6);

                $('#lngText').val(newLatLng.lng);
                $('#latText').val(newLatLng.lat);
            });
        }

        function initMap() {
            try {
                gmap = new google.maps.Map(document.getElementById("map"), {
                    center: originalLatLng,
                    zoom: 18
                });

                marker = new google.maps.Marker({
                    gmap,
                    position: originalLatLng,
                    title: 'Rooftop of Home to be Insured',
                    draggable: true
                });

                
                addMarkerListener(gmap, marker);

                $('#lngText').val(originalLatLng.lng)
                $('#latText').val(originalLatLng.lat)
                document.getElementById("latText").oninput = function () { markerUpdate(gmap) };
                document.getElementById("lngText").oninput = function () { markerUpdate(gmap) };
            } catch (e) {
                console.log(e);
            }

        }


        $('#modalGoogleMapClose').click(function () {

            GetNewLocation();
        });

        $('#modalGoogleMapCancel').click(function () {
            initMap();
        })

        $('#close').click(function () {
            initMap();
        })


        $("#GeoInformation").validate({
            submitHandler: function (form) {
                let isSuccess = GetNewLocation();
                if (isSuccess) {
                    form.submit();
                }
            },
            errorPlacement: function (error, element) {
                error.insertBefore(element);
            },
            onkeyup: false,
            onclick: false
        });

        initMap();

    }); // End document ready
})(this.jQuery);

this is the html

@using some.ViewModel
@model IGoogleMapsCapable

<link href="@Html.ContentVersioned("/Content/GoogleMapStyle.css")" rel="stylesheet" type="text/css" />
<script>
    (g => {
        console.log("loading google maps");
        var h, a, k, p = "The Google Maps JavaScript API", c = "google", l = "importLibrary",
            q = "__ib__", m = document, b = window; b = b[c] || (b[c] = {}); var d = b.maps || (b.maps = {}),
                r = new Set, e = new URLSearchParams, u = () => h || (h = new Promise(async (f, n) => {
                    await (a = m.createElement("script")); e.set("libraries", [...r] + ""); for (k in g) e.set(k.replace(/[A-Z]/g, t =>
                        "_" + t[0].toLowerCase()), g[k]); e.set("callback", c + ".maps." + q);
                    a.src = `https://maps.${c}apis.com/maps/api/js?` + e; d[q] = f; a.onerror = () =>
                        h = n(Error(p + " could not load.")); a.nonce = m.querySelector("script[nonce]")?.nonce || ""; m.head.append(a)
                }));
        d[l] ? console.warn(p + " only loads once. Ignoring:", g) : d[l] = (f, ...n) => r.add(f) && u().then(() =>
            d[l](f, ...n))
            console.log("google maps loaded", h, a, k, p);
    })
        ({
            key: "I have my actual key here",
            v: "quarterly",
        });
</script>

<script src="@Html.ContentVersioned("/Scripts/google-maps.js")"></script>


@Html.HiddenFor(x => x.GoogleMaps.OriginalLat)
@Html.HiddenFor(x => x.GoogleMaps.OriginalLng)
@Html.HiddenFor(x => x.GoogleMaps.NewLat)
@Html.HiddenFor(x => x.GoogleMaps.NewLng)


<div class="alert alert-danger" role="alert">
    <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
    <span class="sr-only">The current Latitude/Longitude is not considered accurate enough to bind the policy. Please enter a new Latitude/Longitude here</span>
    <p>The current Latitude/Longitude is not considered accurate enough to bind the policy. Please enter a new Latitude/Longitude <a class="mimic-hyperlink-text" href="#modalGoogleMap" data-toggle="modal" data-target="#modalGoogleMap">here</a></p>
</div>

<div class="modal fade in" id="modalGoogleMap" tabindex="-1" role="dialog" aria-labelledby="modalGoogleMap" data-backdrop="static" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" id="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <p class="modal-title" id="red-txt">Geolocation did not return as rooftop. Please drag and drop red pin on home location</p>
            </div>
            <div class="modal-body row-fluid">
                <div class="well">
                    <div id="map"></div>
                </div>
                <div class="well">
                    <div id="lngLat">
                        <input type="text" class="lngText" id="lngText" aria-label="Longitude" />
                        <input type="text" class="latText" id="latText" aria-label="Latitude" />
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" name="modalGoogleMapClose" id="modalGoogleMapClose" class="btn btn-primary">Update</button>
                <button type="button" name="modalGoogleMapCancel" id="modalGoogleMapCancel" class="btn" data-dismiss="modal">Cancel</button>
            </div>
        </div>
    </div>
</div>

I have tried a variety of things straight from the google maps javascript api documentation.

if i make the functions in the JS async and use await as it describes in the documentation I get a

Uncaught (in promise) TypeError: r is not iterable error
if i use legacy loading like this

<script async src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"> </script>

I get a blank map still but no errors in console

with the current code this is the caught error in the try catch from the initMap

`TypeError: GMap is not a constructor
    at initMap (google-maps.js:60:24)
    at HTMLDocument.<anonymous> (google-maps.js:182:9)
    at e (jquery-3.4.1.min.js:2:29453)
    at t (jquery-3.4.1.min.js:2:29755)`

I have also tried as per the documentation

async function initMap() {
  const { Map } = await google.maps.importLibrary("maps");

  map = new Map(document.getElementById("map"), {
    center: { lat: -34.397, lng: 150.644 },
    zoom: 8,
  });
}

that results in this error

`Uncaught (in promise) TypeError: r is not iterable
`

on the const { Map } line

Ive even tried renaming Map to GMAp in that const since i believe Map is a reserved word.