0

I am trying to implement addMarkers function and calling "/articles" endpoint to get JSON data. However, while creating infoWindow javascript variable loses value.

function addMarker(place)
{
    var myLatLng = {lat: Number(place.latitude), lng: Number(place.longitude)};
    var marker = new google.maps.Marker({
    position: myLatLng,
    map: map,
    title: place.place_name
    });
    var query = "geo="+place.postal_code;
    var contentString  = "hi there";
    $.getJSON("articles", query)
    .done(function(data, textStatus, jqXHR)
    {
        for(var i=0;i<data.length;i++)
        {
            contentString += data[i].title;
            console.log(contentString);
        }
    })
    var infowindow = new google.maps.InfoWindow({
    content: contentString 
    });
    marker.addListener('click', function() {
    infowindow.open(map, marker);
    });
    markers.push(marker);
}

On clicking my infoWindow only shows "hi there" however, console.log displays entire news title.

1

Some background, skip if you want:

JavaScript can only ever handle one piece of running code at a time. If you did the AJAX request in a synchronous way, waiting for it to complete before you continue, the browser would be blocked until the request succeeds, fails, or times out. The JavaScript way is to initiate something and pass a function to call when finished. That function is called a "callback function". Your code continues, and when the background process has finished, the callback is enqueued for execution (background search term would be "javascript event loop"). Nested callbacks can lead to "callback hell".

There are alternative ways to express the same in a more readable way, jQuery introduced "deferreds" (done is a method of a deferred), standard JavaScript got its version called "promise", where about the same thing is called then, not done.

ES2017 introduces async/await keywords which would allow you to write this kind of asynchronous Promise-based code in a synchronous-looking way. They are relatively widely supported, but I would not use them in production yet (unless you transpile to older standard).

Now to your actual problem:

The JSON call is initiated in your code, but completed at some point after addMarker has finished, then calling the function passed to done. You need to move the part depending on the result of the call (contentString) into that callback function.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .