Javascript Google Map API : Change the content of infowindow using AJAX

Its an interesting subject that how one can change the content of google map’s infowindow dynamically. Many times we need to perform an action which results in change of content of infowindow also.

For example, if we have displayed a like button for a particular place which is showing in the content, and its marker is also showing in map. On clicking on that marker, infowindow will launch. Infowindow will also have the same like button. If user clicks on like button of place which is showing in content then we may need to change the style or text of infowindow’s like button also, whenever infowindow will be launched, to show that it is liked now.

This can be done in two steps, first is using domready event of infowindow and second is using ajax.

First we will have to define the domready event of google map’s infowindow :

//Call domready event of infowindow
google.maps.event.addListener(infowindow_marker, ‘domready’, function() {

// Select the .gm-style-iw div, its the main div from where infowindow html starts
var wpgmp_iwOuter = $(‘.gm-style-iw’);

//Send the wp ajax request (Here you can send ajax request to any platform you are working)

var data = {
‘action’: ‘check_if_liked’,
‘place_id’: iwOuter.find(‘.favourite a’).data(‘place-id’),
};

$.post(ajax_url, data, function(response) {
if (response != 0) {
iwOuter.find(‘.like’).replaceWith(response);
}
});

});

//WP Function where you can handle the ajax request to check whether place is liked or unliked

add_action( ‘wp_ajax_check_if_followed’, ‘check_if_liked’ );
function check_if_liked(){
//check here if place is liked or not by querying database

/**

code

**/

//Now you can send the response

echo ‘<div class=”.liked”>Liked</div>’;
die();
}

Thus, we can easily change the content of infowindow dynamically.

Leave a Reply