4

I would like to display or hide some markers when a user click on a checkbox. I'm using Gmaps.js and the code responsible for this is:

// Check if the user wants to display points of interest
$("#poi").click(function() {
    var poi_markers = [];

    if ($("#poi").is(':checked')) {
        // Get points of interest and display them on the map
        $.ajax({
            type: "POST",
            url: "/ajax/poi.php",
            dataType: "JSON",
            cache: false,
            success: function(data) {
                $.each(data, function(key, value) {
                    poi_marker = {
                        marker: {
                            lat: value.latitude,
                            lng: value.longitude,
                            icon: '/images/marker-sight.png',
                            infoWindow: {
                                content: value.name
                            }
                        }
                    }
                    poi_markers.push(poi_marker);
                });

                console.log(poi_markers);

                map.addMarkers(poi_markers);
            }
        });
    } else {
        map.removeMarkers(poi_markers);
    }
});

Sample JSON:

[{"name":"Biserica Neagra","latitude":"45.640981","longitude":"25.587723"}]

In Firebug I get this error: "uncaught exception: No latitude or longitude defined.".

What am I doing wrong?

Jeff
  • 12,147
  • 10
  • 51
  • 87
Cosmin
  • 864
  • 3
  • 16
  • 34
  • Could you provide a sample of the JSON file? Or even better, a [JS Fiddle](http://jsfiddle.net). – blex Jul 27 '14 at 10:42
  • Sure: `[{"name":"Biserica Neagra","latitude":"45.640981","longitude":"25.587723"}]` – Cosmin Jul 27 '14 at 10:46

2 Answers2

11

Problem #1

The addMarkers() function takes an array of markers as a parameter. But you are giving it an array of objects with a marker property. They should be declared that way:

poi_marker = {
    lat: value.latitude,
    lng: value.longitude,
    infoWindow: {
        content: value.name
    }
}

Problem #2

The removeMarkers() function does not take any parameter because it removes all markers. It should be called that way:

map.removeMarkers();

How to add/remove only groups of markers

For clarity, and since I think you'll figure out how to do this, I'll omit the Ajax part, and assume you have all your markers defined like this after collecting them:

var realMarkers = {},
    gMarkers = {
        bars: [
            {lat:"45.640981",lng:"25.587723",infoWindow:{content:"Irish Pub"}},
            {lat:"45.645911",lng:"25.582753",infoWindow:{content:"Beer King"}}
        ],
        transportation: [
            {lat:"45.645981",lng:"25.590723",infoWindow:{content:"Subway"}},
            {lat:"45.640981",lng:"25.583723",infoWindow:{content:"Train"}},
            {lat:"45.636981",lng:"25.580723",infoWindow:{content:"Airport"}}
        ]
    };

As you can see, I used an Object gMarkers where the g stands for Gmaps.js, because these markers are different from real Google Maps markers, which you'll need for this. The real markers will be stored in the realMarkers variable.

Since Gmaps.js does not provide a way to add/remove only some markers, I created 2 functions, which you can add to your code.

addMarkersOfType()

/* Takes the poi type as a parameter */

GMaps.prototype.addMarkersOfType = function (poi_type) {
    // clear markers of this type
    realMarkers[poi_type]=[];
    // for each Gmaps marker
    for(var i=0; i<gMarkers[poi_type].length; i++){
        // add the marker
        var marker = map.addMarker(gMarkers[poi_type][i]);
        // save it as real marker
        realMarkers[poi_type].push(marker);
    }
}

removeMarkersOfType()

/* Takes the poi type as a parameter */

GMaps.prototype.removeMarkersOfType = function (poi_type) {
    // for each real marker of this type
    for(var i=0; i<gMarkers[poi_type].length; i++){
        // remove the marker
        realMarkers[poi_type][i].setMap(null);
    }
    // clear markers of this type
    realMarkers[poi_type]=[];
}

Example use

$("#bar_poi").click(function() {
    if ($(this).is(':checked')) 
        map.addMarkersOfType("bars");
    else 
        map.removeMarkersOfType("bars");
});

JS Fiddle Demo

blex
  • 24,941
  • 5
  • 39
  • 72
  • I'm using [GMaps.js](http://hpneo.github.io/gmaps/) and that syntax for latitude and longitude is correct. Anyway, I tried your demo, but the marker is still on the map after you uncheck that option. – Cosmin Jul 27 '14 at 11:42
  • Thank you for pointing out that problem with the array. The thing is I have to let the user hide the markers because there are multiple types of markers (points of interest, clubs, bars etc.) and the map will get crowded if markers can't be hidden. – Cosmin Jul 27 '14 at 12:43
  • @Cosmin Gmaps.js does not seem to provide the ability to hide only some markers, it removes them all. You might have to recreate your own function. Please provide a JSON sample with different _poi types_ (with a `type` property for example) and I'll see what I can do. (not in the comments, edit your question) – blex Jul 27 '14 at 12:47
  • I have an ajax request for each type of markers and I hold each json response in an array. So in the end I have the following arrays of markers: "poi_markers", "tickets_centers_markers" etc. – Cosmin Jul 27 '14 at 12:51
  • so... any tips on how can I remove those markers by category? – Cosmin Jul 27 '14 at 16:45
  • Thank you! saved my day :) Great answer great example! Guru! :) – Sergei Zahharenko Apr 08 '16 at 09:58
0

Another solution could be use the method setVisible(true|false) to show or hide the marker without remove it from map.

Pablo
  • 635
  • 1
  • 7
  • 19