20

I'm using the following code to generate marker pins. It loads perfectly, but to the left of this map I have filters. How do I reload the markers without reloading the map? This has been causing some frustration so any help would be appreciated.

Many thanks,

    //Google map results
        var contentStrings = [];
        var infowindow = new google.maps.InfoWindow();
        var mapinited = false;
        var map;
        var myOptions = {
          zoom: 11,
          center: myLatlng,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        var currentinfobox;
        var myLatlng;
        var markersArray=[];
        var LatLngList = [];

$().ready(function() {

    //reinit search 
    if (window.location.hash) {
        submitForm(window.location.hash.replace('#',''));
    }
    else if (readCookie('sf')) {
            //submitForm(readCookie('sf'));
    }

    //init map
    $('#map_view').click(function() {
        if (mapinited) {
            return;
        } else {
            mapinited = true;
            initMap();
        }



    function initMap() {
            locate(["Ireland"],function(result) {
        map = new google.maps.Map(document.getElementById("search_map"), myOptions);
        myLatlng = new google.maps.LatLng(result.lat(),result.lng());

              var key =0;

               $.each(map_results, function(key, value){
        LatLngList[key] = new google.maps.LatLng(value.lat,value.long)
        contentStrings[key] =
                '<div id="ginfo_content" class="map-pop-up">'+
                  '<span class="content-top">&nbsp;</span>'+
                  '<div class="content-middle">'+
                    '<div class="map-filler">'+
                      '<a class="map-close" href="javascript:;" onclick="infowindow.close();" title="Close">x</a>'+
                      '<br class="clearfix">'+
                      '<div class="map-pop-up-left">'+
                        '<a href="profile.php?id='+ value.user_id +'"><div class="thumbnail"><img src="'+ value.image +'" width="64" height="64"></div></a>'+

                        '<a href="javascript:;" class="user-contact" onClick="to='+ value.user_id +';contact_showCaptcha();pop_up(\'pop-up-contact\');">Contact</a>'+

                      '</div>'+
                      '<div class="map-pop-up-right">'+
                        '<h2><a href="profile.php?id='+ value.user_id +'">'+ value.firstname +' '+value.lastname+',</a> '+ value.address +'</h2>'+
                        '<p>'+ stripslashes(value.about) +'</p>'+
                      '</div>'+
                      '<br class="clearfix">'+
                      '<div class="map-pop-up-footer"><a href="profile.php?id='+ value.user_id +'" class="view-profile">View Profile</a><span class="telephone">Telephone: '+ value.phone +'</span></div>'+
                    '</div>'+
                  '</div>'+
                  '<span class="content-bottom">&nbsp;</span>'+
                '</div>';
                 key++;
               });//end each

                map_results="";

        google.maps.event.addListener(infowindow, 'domready', function() {
            var infocontent = $('#ginfo_content').clone();
            var l = $('#ginfo_content').parent().parent().parent().addClass('original_popup').html('');
            $('.original_popup').append(infocontent).show();
            $('.original_popup').css('width','360px').css('height','230px').css('left','+=27px').css('top','+=65px');
        });

        var zoomChangeBoundsListener = google.maps.event.addListener(map, 'zoom_changed', function() {
            if (this.getZoom() > 14) // Change max/min zoom here
                this.setZoom(14);        
            google.maps.event.removeListener(zoomChangeBoundsListener);
        });
        var infoboxlistener = google.maps.event.addListener(map, 'zoom_changed', `enter code here`function() {
            infowindow.close();
        });
        loadMapInit(LatLngList,contentStrings);

    });
    }

    });

  });

3 Answers 3

23

Hopefully this is answering what you're asking:

When you create a marker, you can use the 'map' parameter to set its map and have it show up. Or, if you want to tie it to a filter, you can ignore the map paramter and use marker.setMap(map) later.

// To add the marker to the map, use the 'map' property
var marker = new google.maps.Marker({
    position: myLatlng,
    map: map,
    title:"Hello World!"
});

If you want to 'remove' and 'add' markers with events, you can use marker.setMap(null) to remove the marker and marker.setMap(map) to re-add it.

var marker = new google.maps.Marker({
    position: myLatlng,
    title:"Hello World!"
});

// To add the marker to the map, call setMap();
marker.setMap(map);

// To remove the marker from the map
marker.setMap(null);

https://developers.google.com/maps/documentation/javascript/markers

Update: So if you wanted to 'reload' the markers, you could traverse through and array of currently active markers, set their maps to null, and then reset them on the map.

1
  • 1
    Your very welcome. When I've done this in the past, I've kept an array of all markers on the page (use a hashed array if they are in different 'layers') and to trigger each layer on and off, simply traverse through that array index and set the markers accordingly. Commented Mar 5, 2014 at 14:47
1

My page loads maps in two scenarios 1) first load 2) ongoing refreshing of a google map through ajax calls.

The following worked for me

<input type="hidden" id="lonDeg"><!--route lat to here via ajax call-->
<input type="hidden" id="latDeg"><!--route lon to here via ajax call-->

 <script>
  var map;
  function initMap() {
    // these two lines are the only variation from the native google 
    // API code.  They allow for dynamic updates of the lon/lat (below)
    var lonDeg = parseFloat($("#lonDeg").val());
    var latDeg = parseFloat($("#latDeg").val());

    var midp = {lat:latDeg, lng:lonDeg };

    map = new google.maps.Map(document.getElementById('map'), {
      scaleControl: true,
      center: midp,
      zoom: 10

    });
     var marker = new google.maps.Marker({map: map, position: midp});
        marker.addListener('click', function() {
      infowindow.open(map, marker);
    });
  }
    </script>

The event trigger in my case a button

<button id="getNextMap">Go to Next Map</button>

Then finally the javascript that makes it all happen

    var qstring = 'myArgsToPass';
    var csv  = new Array();

    $.ajax({
        url: 'mapProfileGrabber.php',
        type: 'POST',
        data: {q:qstring},
        success: function(data) {
            csv = data.split(",");                        
            $("#lonDeg").val(csv[0]);
            $("#latDeg").val(csv[1]);

            initMap();
    }
0

In my case, I'm using SVG icons, and I'm changing the strokeColor in code, after the marker (and its icon) are on the map.

To have the map display the new color, I simply call setMap again:

marker.setMap(map);

I find no need to remove it first with marker.setMap(null);

I have a hunch this will work with other changes to the marker, like its icon's URL, etc.

Not the answer you're looking for? Browse other questions tagged or ask your own question.