What is the process of integrating data from the OpenWeatherMap API into the WindowInfo feature of Google Maps?

My current project involves retrieving weather information from the openweathermap API and displaying it in an infowindow on Google Maps. However, there seems to be an issue where I am getting data from the previous marker instead of the current one.

var map;
        var markers = [];
        var s = "";
        function initMap() {
            var currentLat;
            var currentLng;
            var coords;
            var contentString;
            map = new google.maps.Map(document.getElementById('map'), {
                center: { lat: 40.295308, lng: 62.164714 },
                zoom: 4
            });
            // get lng and lat
            google.maps.event.addListener(map, 'click', function (event) {
                currentLat = event.latLng.lat();
                currentLng = event.latLng.lng();
                coords = { lat: currentLat, lng: currentLng };
                getWeather(coords);
                addMarker(coords);
                s = "";
            });

            function addMarker(coords) {
                var marker = new google.maps.Marker({
                    position: coords,
                    map: map
                });

                var infoWindow = new google.maps.InfoWindow({
                    content: s
                });
                marker.addListener('click', function () {
                    infoWindow.open(map, marker);
                });
                ///
            }

        }

        function getWeather(coords) {
            fetch('https://api.openweathermap.org/data/2.5/weather?lat=' + coords.lat + '&lon=' + coords.lng + '&units=metric&appid=MYAPI')
                .then((response) => {
                    return response.json();
                })
                .then((myJson) => {

                    console.log(myJson);
                    s += myJson.name;
                }).catch((err) => {
                    console.log("Error: " + err);
                });
        }

I have attempted to use a global string variable and also experimented with using setTimeOut on the getWeather function multiple times, but I cannot seem to retrieve the information before sending the point to the map.

Answer №1

When populating the global variable s with the result of an asynchronous call to retrieve weather information, it's important to consider that the call may not have completed by the time addMarker() is executed to create the InfoWindow.

To ensure synchronization and avoid reliance on the global s variable, make sure to call the addMarker function only after getWeather has successfully retrieved the data. Remove the current invocation of addMarker and update the method signature as follows;

function addMarker(coords, s) { ... }

Next, modify the getWeather function implementation like so;

function getWeather(coords) {
    fetch('https://api.openweathermap.org/data/2.5/weather?lat=' + coords.lat + '&lon=' + coords.lng + '&units=metric&appid=MYAPI')
        .then((response) => {
                return response.json();
        })
        .then((myJson) => {
                addMarker(coords, myJson.name);
        }).catch((err) => {
                console.log("Error: " + err);
        });
}

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

Leveraging Underscore in ReactJS applications

I'm encountering an issue with integrating Underscore into my ReactJS project. When I attempt to run my ReactJS class, the following error arises: Uncaught ReferenceError: _ is not defined index.html <html> <head> <meta http-equi ...

What is the best way to send a JavaScript variable to Django using AJAX?

I am facing an issue while trying to pass an array in json format using ajax to my django views. Even though I receive a status of 200 indicating that the POST request has been successfully made, when I attempt to display the data passed in another templat ...

Pass the form data to the next page with javascript in HTML

While working on a website for a power plant, I encountered some issues that require assistance. The main problem is that our client does not want to set up a database on their server. This means I can only use html, javascript, and a bit of php. There is ...

Issue with displaying props value at the beginning of a function in ReactJS render

But the this.props.NotesAll object retrieved from another component is displaying under the render() method. However, when I attempt to use this.props.NotesAll above the render in a function to manipulate the objects and check their values with console.log ...

Combining an array of intricate data models to create

Currently, my setup involves using Entity Framework 7 in conjunction with ASP.NET MVC 5. In my application, I have various forms that resemble the design showcased in this image. By clicking on the "new" button within these forms, a Bootstrap modal like t ...

organize the values based on their priority using reactjs

I'm facing a challenge involving two arrays of objects: array1 and array2. I need to display only three values from both arrays, with priority given to array1. The requirements are as follows: if array1 contains 3 elements, all three should be shown. ...

Accessing information from Next.js API endpoint in a Next.js web application

Currently, I am in the process of developing a web application using Next.js APP Router for both the frontend and backend components. The frontend takes care of rendering the user interface, while the backend comprises API routes. I require some guidance o ...

`The height attribute of the textarea element is not being accurately adjusted`

When I tried to match the width(178px) and height(178px) of my table to the width and height of a text area upon clicking a button, I encountered an issue. While setting the width works perfectly fine, the height is being set to only 17px. It seems like ...

Transferring data via AJAX technology

My goal is to empower the ability to upload files using AJAX. I attempted to utilize (JavaScript) in this manner: $("input[type='file']").change(function(){ var file = document.getElementById("uploadelement").files[0]; $.ajax ...

steps to create a personalized installation button for PWA

Looking to incorporate a customized install button for my progressive web app directly on the site. I've researched various articles and attempted their solutions, which involve using beforeinstallprompt. let deferredPrompt; window.addEventListener(& ...

Attempting to update an AJAX field with the returned value, but it only updates after clicking away from it

Image of form utilizing AJAX & JS The current setup involves a maintainer that uses AJAX to update the "Calc" field in response to a number entered in the "Order No" field. The issue is that the "Calc" field does not update immediately after typing in the ...

Challenges with ReactToPrint Library and Optimizing Layout for Thermal Printer

Working on a React.js project, I have been using the ReactToPrint library to print a specific section of my page. However, I am facing an issue where the page size remains too large and important content is being left out in the printed receipt. It seems ...

There appears to be an issue where the session object cannot be retrieved by the Struts2 action

I have a struts2 action that is invoked by a JavaScript function. The JavaScript function uses uploadify to enable multiple file uploads: <script type="text/javascript"> $(document).ready(function() { $("#fileupload").uploadify({ ...

Verify whether the document includes a class that closely matches the provided string using Javascript

I need help identifying elements that include the letters 'ad'. For example: <iframe class="container" /> <!-- Not relevant --> <a class="adp" /> <!-- Relevant --> <a class="adleft" /> ...

Populate my empty arrays with information retrieved from Firebase

I am currently working on creating a "single client" view for my application. Each client has a first name (prenom) and a last name (nom). However, even though my application recognizes that these values exist for each client, they do not appear on the scr ...

Unable to modify translation values in an existing ngx-translate object

I am facing an issue where I am unable to change the value of an object property within a translation JSON file using ngx translate. Despite attempting to update the value dynamically when receiving data from an API, it seems to remain unchanged. I have t ...

Enhance your loader functionality by dynamically updating ng-repeat using ng-if

To better illustrate my issue, here is a link to the fiddle I created: https://jsfiddle.net/860Ltbva/5/ The goal is to show a loading message while the ng-repeat loop is still loading and hide it once all elements have been loaded. I referenced this help ...

Placing a function within an array raises the question: why is the array's value represented as an integer?

There's something puzzling happening in my code. I've placed a setTimeout function inside an array, but when I check the contents of the array using console.log(arr), it only shows an integer value. How is this possible? See the code snippet belo ...

Is it possible to dynamically change HTML content by utilizing a JSON file?

Looking to implement a JavaScript loop (using jQuery) that can dynamically populate the HTML file with content from a JSON file based on matching <div> ids to the JSON "id" values. The solution should be scalable and able to handle any number of < ...

The alert message fails to appear during an Ajax request

I'm having trouble understanding why the Ajax function in this code snippet is not triggering the success or error functions: function get_cust_key(custid) { $.ajax({ type: "POST", url: 'http://localhost/Test/index.php/getCust ...