Search code examples
javascriptcssgoogle-mapscodepen

(Javascript) Passing variables in Codepen from JS window into HTML <script></script> template


I'm doing a weather/map web app. Based on the user's latitude and longitude it will get you the weather and location on a Map (Google maps). I'm seeing that when using the Google Maps API in Codepen you cannot put it in the Js window, instead you gotta put it in the HTML template in between <script></script> tags.

That's fine but the problem is that I need to pass the latitude and longitude variables from the JS window in there so I can search the location. How would I do this? Codepen can be a little tricky at times.

Hopefully I'm making sense and here's the Codepen:

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

Thanks

Just putting a script below because I'm requireing to include code, please see the Codepen link.

<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=AIzaSyCB4SQpFr1XLzTuYlQF_KTBixLCUQoRcOY&callback=initMap">
    </script>
</body>

</html>

Solution

  • If I understood correctly, you can just declare your map as a global variable an access it from your script. I called here myMap.

    Something like that:

    In 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());
    

    Working code: https://codepen.io/mrlew/pen/MJzqzZ