I'm experiencing what I think may be a caching or asynchronous error, but I'm not sure.
Essentially, I have a javascript function to grab the Google Places image for a place the user has inputted.
Here's that function:
function getInitialImage(placeIdentifier) {
service = new google.maps.places.PlacesService(document.createElement('div'));
request = {placeId: ""+placeIdentifier+""};
service.getDetails(request, function(result, status) {
if (status !== google.maps.places.PlacesServiceStatus.OK) {
console.log(status);
return;
} else {
photoUrl = result.photos[0].getUrl({maxWidth: 300});
sessionStorage.setItem("photoUrl", photoUrl);
htmlAttr = result.photos[0].html_attributions;
sessionStorage.setItem("htmlAttr", htmlAttr);
}
})
photoUrl = sessionStorage.getItem("photoUrl");
htmlAttr = sessionStorage.getItem("htmlAttr");
return {
photoUrl: photoUrl,
htmlAttr: htmlAttr
};
}
This is how I'm calling and using the function on my "main" page:
placeIdent = "<?php echo $placeID?>";
console.log(placeIdent);
photoUrl = "";
var results;
results = getInitialImage(placeIdent);
photoUrl = results.photoUrl;
var randStringForUrl = Math.random().toString(36).substring(7);
photoUrl = photoUrl + '?' + randStringForUrl;
htmlAttr = results.htmlAttr;
console.log(photoUrl);
I'm then updating the source of the image in my page like this:
<img id="displayImage" style="height: 200px"></img>
<script>document.getElementById('displayImage').src = photoUrl
;</script>
Note: console.log(placeIdent)
displays what I would expect - the user's updated placeID, but for some reason console.log(photoUrl)
is displaying the "old" photoUrl (from a previous request). This is resolved if I manually refresh the page.
Also note, from some previous research I determined that the image may be cached so I appended the URL with '?' + randStringForUrl
in an effort to avoid caching.
Any thoughts on why photoUrl
and subsequently the image are not updating until I refresh, even though the placeIdent
(i.e. Google PlaceID) is updating?
Thank you!!
Posting my solution for any other newbies. I ended up using a timeout function:
window.onload = function() {
setTimeout(function(){
document.getElementById('displayImage').src = photoUrl;
}, 200);
}
Which did the trick. My html code has a placeholder loading gif, which is updated 200 milliseconds after page load.
HTML:
<div style="height: 250px;"><img src="images/loading.gif" id="displayImage"></img></div>
Hope this helps someone!