Oliver Evans
Oliver Evans

Reputation: 989

Changing and saving content inside info window after close

I have a map that geocodes locations retrieved from JSON and sticks a marker on the map.

The markers also have an infowindow that shows the markers name and rating.

There's a button inside an infowindow that increments a rating counter when you click a button.

The initial counter is retrieved from JSON.

Annoyingly, when the info window closed and reopen, the counter value resets.

I tried populating an object with all of the marker ratings, updating the object when the button is clicked and then output the rating from the object inside the contentString for the infowindow. This didn't work and the same initial rating counter was shown after re-opening the infowindow.

My code is below, any help would be appreciated.

var map;
var geocoder;
var infowindow;
var rating;

function initMap() {
    var mapElement = document.getElementById("map_canvas");

    geocoder = new google.maps.Geocoder();

    var mapOptions = {
        center: new google.maps.LatLng(53.481949, -2.237430),
        zoom: 7,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    infowindow = new google.maps.InfoWindow();

    map = new google.maps.Map(mapElement, mapOptions);
}

$(document).on('click', '#been-there', function(event){
    var entryID = $(this).data('entry-id');
    var rating = $(this).data('rating');
    var dataString = 'id='+ entryID;

    rating++;

    $.ajax({
        type: "POST",
        url: "db-been-there.php",
        data: dataString,
        cache: false,
    }).success(function(html){
        console.log(html);
    }).fail(function(html){
        console.log(html);
    });

    $('#rating').html(rating);

});

$.getJSON("db-output.php", function(dbJSON) {
    $.each(dbJSON, function(key, data) {

        var url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + data.lat + "," + data.lng + "&result_type=sublocality|political&key=AIzaSyCsY-LOPL7dGbA1ShBEu7zMO8_GaSBA3Vg";

        $.getJSON(url, function(reverseGeo) {
            var postal_town = reverseGeo.results[0].formatted_address;

            geocoder.geocode( { 'address': postal_town}, function(results, status) {
                if (status == 'OK') {

                    var marker = new google.maps.Marker({
                        map: map,
                        position: results[0].geometry.location,
                        title: data.name
                    });

                    var contentString = '<div id="content">'+
                        '<h1>' + data.name + '</h1>' +
                        '<button id="been-there" data-rating="' + data.rating + '" data-entry-id="' + data.id + '">Seen it</button>' +
                        '<p><strong>Rating: </strong><span id="rating">' + data.rating + '</span></p>' +
                        '</div>';

                    marker.addListener('click', function() {
                        infowindow.setContent(contentString);
                        infowindow.open(map, marker);
                    });

                } else {
                    alert('Geocode was not successful for the following reason: ' + status);
                }
            });
        });
    });
});

EDIT: Resolved code and JSFiddle below

Resolved JSFiddle: https://jsfiddle.net/BleepyEvans/3czqmqav/

var locations = [
    {
        "id": "1",
        "name": "Location 1",
        "lat": "53.408371",
        "lng": "-2.991573",
        "rating": "17"
    },
    {
        "id": "2",
        "name": "Location 2",
        "lat": "53.789528",
        "lng": "-2.969411",
        "rating": "8"
    },
]

var map;
var geocoder;
var infowindow;
var rating;
var markers = [];

function initMap() {
    var mapElement = document.getElementById("map_canvas");

    geocoder = new google.maps.Geocoder();

    var mapOptions = {
        center: new google.maps.LatLng(53.481949, -2.237430),
        zoom: 7,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    infowindow = new google.maps.InfoWindow();

    map = new google.maps.Map(mapElement, mapOptions);
}

$(document).on('click', '#been-there', function(event){
    var entryID = $(this).data('entry-id');
    var dataString = 'id='+ entryID;

    rating = markers[entryID].rating;
    rating++;

    markers[entryID].rating = rating;

        console.log(markers[entryID].rating);

    $('#rating').html(rating);

});

$.each(locations, function(key, data) {

    var url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + data.lat + "," + data.lng + "&result_type=sublocality|political&key=AIzaSyCsY-LOPL7dGbA1ShBEu7zMO8_GaSBA3Vg";

    $.getJSON(url, function(reverseGeo) {
        var postal_town = reverseGeo.results[0].formatted_address;

        geocoder.geocode( { 'address': postal_town}, function(results, status) {
            if (status == 'OK') {

                var marker = new google.maps.Marker({
                    map: map,
                    position: results[0].geometry.location,
                    title: data.name,
                    rating: data.rating
                });

                markers[data.id] = marker;

                console.log(markers[data.id].rating);

                marker.addListener('click', function() {
                        var contentString = '<div id="content">'+
                    '<h1>' + data.name + '</h1>' +
                    '<button id="been-there" data-rating="' + data.rating + '" data-entry-id="' + data.id + '">Been There</button>' +
                    '<p><strong>Rating: </strong><span id="rating">' + markers[data.id].rating + '</span></p>' +
                    '</div>';

                    infowindow.setContent(contentString);
                    infowindow.open(map, marker);
                });

            } else {
                alert('Geocode was not successful for the following reason: ' + status);
            }
        });
    });
});

Upvotes: 0

Views: 644

Answers (1)

duncan
duncan

Reputation: 31912

Rather than just create an HTML string which includes the rating data that you assign to your infowindow, I'd add the rating value to the Marker object itself.

var marker = new google.maps.Marker({
    map: map,
    position: results[0].geometry.location,
    title: data.manufacturer_name,
    rating: data.rating
});

Save those markers in an object keyed on their ID:

markers[data.id] = marker;

Then when the user clicks the button, update that value:

$(document).on('click', '#been-there', function(event){
    var entryID = $(this).data('entry-id');
    rating = markers[entryID].rating;
    rating++;

And update the value on the Marker:

markers[entryID].rating = rating;

If it doesn't work directly accessing the rating property on the markers, you might need to use:

markers[entryID].get('rating');
markers[entryID].set('rating', rating);

Upvotes: 1

Related Questions