Using Javascript to pass variables from the JS window in Codepen to an HTML <script></script> template

I am currently working on a weather and map web application. This app will display the weather at the user's location based on their latitude and longitude, as well as show their location on a map using Google Maps. I have encountered an issue while using the Google Maps API in Codepen - it seems that it cannot be placed directly in the JS window but must be included in the HTML template between <script></script> tags.

While this is not a major problem, I need to figure out how to pass the latitude and longitude variables from the JS window to the HTML template in order to search for the location. Figuring this out has proven challenging due to the nuances of Codepen.

If you could take a look, here is the link to the Codepen:

https://codepen.io/tadm123/pen/OWojPx

Thank you for your help!

Since I am required to include code, below is a simplified version of the HTML template. Please refer to the Codepen link for the complete code snippet.

<html>
<head>
  <title>Weather App</title>
</head>

<body>
  <div>
   <div class = "container-fluid" id="box">
     <p id="country"></p>
     <p id="name"></p>
     <p id="weather"></p>
     <p id="celsius"></p>
     <p id="fahrenheit"></p>
     <p id="humidity"></p>

     <img src="aa" alt="Weather icon">

  </div>


<h3>You are here!</h3>
    <div id="map"></div>
    </div>


    <script>
      function initMap() {
        var uluru = {lat: -25.363, lng: 131.044};    
        var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 4,
          center: uluru
        });
        var marker = new google.maps.Marker({
          position: uluru,
         map: map
       });
      }
    </script>
  <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
    </script>
</body>

</html>

Answer №1

It appears that you can simply define your map as a global variable and access it within your script. I have named mine myMap.

Here is an example:

Within your <script> tag:

var myMap = null;

function initMap() {

    /* ... */

    myMap = new google.maps.Map(
        document.getElementById('map'),
        {
            zoom: 4,
            center: uluru
        }
    );
}

Then, in your AJAX callback:

/* add marker */
var marker = new google.maps.Marker({
    position: {
        lat: lat,
        lng: long
    },
    map: myMap
});   

/* center in marker */
myMap.panTo(marker.getPosition());

See the working code here: https://codepen.io/mrlew/pen/MJzqzZ

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Echo a PHP submit button that is capable of executing some JavaScript code

My current challenge involves a script that retrieves specific values from a database and displays them as required. However, I am now attempting to include a column with buttons in each row of the output. These buttons should execute a JavaScript functi ...

The blinking cursor in Google Docs is known as "kix-cursor-caret."

Although I adore Google Docs, I can't help but find the blinking cursor a bit too distracting for my liking. It seems that the latest version of Google Docs fails to comply with the operating system's setting for displaying a solid, non-blinking ...

Adding a new HTML element to each ng-repeat iteration in AngularJS

Can you help me find a solution for inserting a <p> tag in the DOM for each item in my ng-repeat loop? Here is the array of objects I am using for the ng-repeat: $scope.items = [ {name: "john", paragraph:"<p>hi, im john</p>"}, {nam ...

How to style the background color of the first column in an HTML table that includes rowspan

Here is a simple example of a table. I want the header row to be grey, alternate rows below it to be yellow, and the first column to be orange. I'm having trouble achieving this with CSS. How can I do this without individually styling each cell? View ...

What is the best way to verify values in Vuejs based on their length?

<button type="submit" :disabled="(user.password && !$v.user.password.valid) || (user.confirmPassword && !$v.user.confirmPassword.sameAsPassword)">sda </button> By implementing a method based on character len ...

Can one access console and localstorage through android studio?

Is there a way to detect if LocalStorage is being saved on an Android device from Android Studio in an application with a WebView? Also, can javascript code be executed from Android Studio similar to running it in a Chrome console? ...

Playing sound files on Angular using Howler.JS

I am currently trying to incorporate the ability to play an mp3 file within a Cordova + Ionic hybrid app. The sound file is located at: www/sounds/dubstep/sound.mp3 I am attempting to play the file from a service placed in /www/scripts/services/global.j ...

Cross-Origin Resource Sharing (CORS) issue: The Access-Control-Allow-Headers in preflight response does not allow the Authorization request header field

I am currently attempting to send a request from one localhost port to another. Specifically, I am utilizing angularjs on the frontend and node on the backend. Given that this is a CORS request, in my node.js code, I have implemented the following: res.h ...

Getting information from MongoDB using Node.js and Angular

Currently, I am facing difficulty in retrieving data from MongoDB (I'm also using Mongoose) and sending it to Angular in order to populate the ng-repeat list with the retrieved data. I have managed to either display the data on a blank page directly f ...

Determine whether any property within the object is currently null

I am working with an array of objects called data, each object in the array having multiple properties, some of which may have null values. https://i.sstatic.net/hc5O3.png My goal is to filter through this array and eliminate any object that contains a p ...

Inquire regarding the header image. Can you confirm if the current HTML and CSS for this is the most efficient approach?

This is a preview of my website in progress (Disclaimer: I'm currently learning HTML to build this site, design comes next. I know it's not the conventional way to design a site, but oh well) Check out the site here Is the HTML code for the hea ...

What triggers the activation of the inline formatting context in this particular scenario?

MDN provides insight about the img element in regard to styling with CSS, highlighting how images interact within an inline formatting context. The positioning of images when used in-line can be affected by vertical-align: baseline due to <img> not ...

The JavaScript counterpart to jQuery's click event handler

I'm trying to figure out how to achieve the same effect as this jQuery code. var divQuery = $('.html5gallery-thumbs-0').children(); divQuery.on('click', function () {...} I attempted it like this: var divQuery = document.g ...

Steps for creating a button that increments by using ng loop:1. Begin

I am attempting to create a button that can be used to increment and decrement. However, I am facing an issue where all input fields are being affected instead of just one. This is the code in body.component.html <div class="items-detail-detail" *n ...

What is the best way to customize the appearance of a mat-checkbox in Angular using Angular Material?

Is there a way to customize the appearance of a mat-checkbox that actually works? I've tried various solutions without success. I attempted to disable view encapsulation and use classes like mdc-checkbox__background, but nothing changed. Even applyin ...

Managing extensive geographical information through HTTP

What is the most efficient way to transmit a substantial volume of map information via HTTP for rendering on the client side? There must be a more effective approach than simply transmitting a JSON file containing all map data. I am interested in how maj ...

The "html" element fails to achieve a full height when applying a 100% height setting

I am facing a height problem of 100% <!doctype html> <html> <head> <meta charset="utf-8"> <title>My Dreamweaver Website</title> <link rel="stylesheet" href="style.css"> </head> <body> <section clas ...

What is the method for consistently rotating the object regardless of the camera's orientation?

I am trying to rotate an object along the world axis while considering the direction of the camera, so that the rotation remains consistent even when the camera changes direction. The current code allows me to rotate a sphere along the world axis. However ...

javascript doesn't execute the php script

Hello everyone, I've been working on a project for quite some time and I’ve encountered an issue that I can't seem to solve. Hopefully, you can help me out with this. I have a digital LED strip controlled by an Arduino, which in turn is control ...

Is it impossible to run a node.js application as a background service using npm-windows on Windows operating system?

I am attempting to utilize node-windows for executing my script as a background service. After installing node-windows globally and linking it, I created the following script: var Service = require("node-windows").Service; console.log("ent ...