Loneept
Loneept

Reputation: 37

Google map API, add marker in ajax after initialize the map

I know there have been some questions with related title, but I didn't find the answer that would suit me.

Here is my issue :

I am trying to print a map, with multiple marker in it, generated via a database. I have, below the map, some checkbox that would allow me to filter the marker on the map.

So, the first time I am loading the map, everything is well filtred (depending on what is checked by default), by I don't really understand how to add / remove marker from the map once it is already initialized. Do I have to reload the map, or am I missing something ?

Here is the relevant code :

<form>
<input class="test" type="checkbox" name="type" value="1" onclick="test()" checked/>1<br/>
<input class="test"type="checkbox" name="type" value="2" onclick="test()" checked/>2<br/>
<input class="test"type="checkbox" name="type" value="3" onclick="test()" checked/>3<br/>
<input class="test"type="checkbox" name="type" value="4" onclick="test()" checked/>4<br/>

<script>
var checkedValues = $('input:checkbox:checked').map(function() {
    return this.value;
}).get().join('-');

function fetchPlace(filtreType){

$.ajax({
    url:    "ajaxmap.php?type=" + filtreType,
    type : 'GET',
    dataType: 'json',
    success : function(data) {

     // Loop through our array of markers & place each one on the map  
        for( i = 0; i < data.marker.length; i++ ) {
            var myLatlng = new google.maps.LatLng(data.marker[i].log,data.marker[i].lat);
            var marker = new google.maps.Marker({
                  position: myLatlng,
                  map: map,
                  title: 'Hello World!'
              });
        }
    }
    ,
    error: function(){
        /// traiter les erreur
    },
    async : true
});
};
function test (){
var checkedValues = $('input:checkbox:checked').map(function() {
        return this.value;
    }).get().join('-');
fetchPlace(checkedValues);
};
fetchPlace(checkedValues);

Thanks for any help you could provide.

Loneept

Upvotes: 0

Views: 8734

Answers (2)

MrUpsidown
MrUpsidown

Reputation: 22489

Here is what I did:

The 2 arrays of coords correspond to what you would get in your AJAX success.

markers is an array. In the addMarkers function, I create an array with the filter type value. Something like markers[filterType] = new Array();

This way, you can now easily identify markers of each type and toggle them on or off.

Of course you will need to adapt this to your needs (I used buttons, you used checkboxes, etc.) and maybe you only need to load your markers once, etc. But you should be able to get the idea.

var map;
var markers = new Array();

var coords_1 = [
    new google.maps.LatLng(60.32522, 19.07002),
    new google.maps.LatLng(60.45522, 19.12002),
    new google.maps.LatLng(60.86522, 19.35002),
    new google.maps.LatLng(60.77522, 19.88002),
    new google.maps.LatLng(60.36344, 19.36346),
    new google.maps.LatLng(60.56562, 19.33002)];

var coords_2 = [
    new google.maps.LatLng(59.32522, 18.07002),
    new google.maps.LatLng(59.45522, 18.12002),
    new google.maps.LatLng(59.86522, 18.35002),
    new google.maps.LatLng(59.77522, 18.88002),
    new google.maps.LatLng(59.36344, 18.36346),
    new google.maps.LatLng(59.56562, 18.33002)];

function initialize() {

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

    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

    $('button').on('click', function() {

        if ($(this).data('action') === 'add') {

            addMarkers($(this).data('filtertype'));

        } else {

            removeMarkers($(this).data('filtertype'));
        }
    });
}

function addMarkers(filterType) {

    var temp = filterType === 'coords_1' ? coords_1 : coords_2;

    markers[filterType] = new Array();

    for (var i = 0; i < temp.length; i++) {

        var marker = new google.maps.Marker({
            map: map,
            position: temp[i]
        });

        markers[filterType].push(marker);
    }
}

function removeMarkers(filterType) {

    for (var i = 0; i < markers[filterType].length; i++) {

        markers[filterType][i].setMap(null);
    }
}

initialize();

JSFiddle demo

So in your case, you could do:

var markers = new Array(); // declare this at the beginning of your script

...

// Loop through our array of markers & place each one on the map  

markers[filtreType] = new Array();

for (i = 0; i < data.marker.length; i++) {
    var myLatlng = new google.maps.LatLng(data.marker[i].log, data.marker[i].lat);
    var marker = new google.maps.Marker({
        position: myLatlng,
        map: map,
        title: 'Hello World!'
    });

    markers[filtreType].push(marker);
}

Edit:

Another solution would be to add the filter type to the marker itself and push all markers to the same array. You can still identify them.

var markers = new Array(); // declare this at the beginning of your script

...

// Loop through our array of markers & place each one on the map
for (i = 0; i < data.marker.length; i++) {
    var myLatlng = new google.maps.LatLng(data.marker[i].log, data.marker[i].lat);
    var marker = new google.maps.Marker({
        position: myLatlng,
        map: map,
        title: 'Hello World!',
        filterType: filtreType
    });

    markers.push(marker);
}

Now if you want to remove markers of a certain filter type you can do:

function removeMarkers(filterType) {

    for (var i = 0; i < markers.length; i++) {

        if (marker.filterType === filterType) {

            markers[i].setMap(null);
        }
    }
}

Note: I don't know if it's a typo, but make sure you don't mess up with filterType and filtreType. I would change everything to filterType to avoid confusion...

Upvotes: 3

dmgig
dmgig

Reputation: 4568

The main thing is you need an array to store the references to your markers in, then you can loop through all of them and either set their "map" property to null, or just delete the array altogether.

You can try to do like so:

function fetchPlace(filtreType){

  var markers = [];

    $.ajax({
        url:    "ajaxmap.php?type=" + filtreType,
        type : 'GET',
        dataType: 'json',
        success : function(data) {

         // Loop through our array of markers & place each one on the map  
            for( i = 0; i < data.marker.length; i++ ) {
                var myLatlng = new google.maps.LatLng(data.marker[i].log,data.marker[i].lat);
                var marker = new google.maps.Marker({
                      position: myLatlng,
                      map: map,
                      title: 'Hello World!'
                  }); /* <----- AT THIS POINT, MARKER IS CREATED AND PLACED ON THE MAP BY SETTING "map" PROPERTY */
               markers.push(marker); /* <----- HERE YOU ARE STORING THEM, AND YOU CAN ACCESS THEM LATER IN YOUR FUNCTION */

            }
        }
        ,
        error: function(){
            /// traiter les erreur
        },
        async : true
    });



}

I believe what will happen here (though not tested) is that when you fire fetchPlace again, all of your original markers will be cleared, then the new ones added in the loop again.

Upvotes: 1

Related Questions