• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1023
  • Last Modified:

Google Maps API v3 - Redrop my markers and center

I have an array setup for various objects, however I would like to get it to redrop the icons and center / zoom out to the map based on where the icons are.

I have tried using setMap(null) to clear the markers, but was having issues with the icon reloading. When there is some overlay with the icons it flickers slightly so I was hoping to use the drop method instead; similar to this link https://google-developers.appspot.com/maps/documentation/javascript/examples/marker-animations-iteration

I would like it to redrop all the icons if possible, depending on the category that is visible.
The current code below show and hides the appropriate icons, I just need to working the drop / centering function

	var map;
  function initialize() {
		
        var centerMap = new google.maps.LatLng(44.3019727, -78.3539062);

        var myOptions = {
            zoom:13,
            center: centerMap,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }

        var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

        setMarkers(map, sites);
	    infowindow = new google.maps.InfoWindow({
                content: "loading…"
            });

      
    }

  var sites = [
    
         	
    	     		['TVM Apartments', '44.278509', '-78.3742282',1,'<h4>TVM Apartments, ON</h4><a href ="http://tvmgroup.onroad.org/residential/tvm-apartments/">More Info</a>', 'two three '],
  	    	  
         	
    	     		['TVM Manor', '44.309494', '-78.325782',1,'<h4>TVM Manor, ON</h4><a href ="http://tvmgroup.onroad.org/residential/tvm-manor/">More Info</a>', 'one two '],
  	    	  
         	
    	     		['TVM Tower Residences', '44.3070732', '-78.3225406',1,'<h4>TVM Tower Residences, ON</h4><a href ="http://tvmgroup.onroad.org/residential/tvm-tower-residences/">More Info</a>', 'one two three '],
  	    	  
         	
    	     		['TVM Peterborough', '44.3071462', '-78.3204109',1,'<h4>TVM Peterborough, ON</h4><a href ="http://tvmgroup.onroad.org/residential/tvm-peterborough/">More Info</a>', 'bachelor one two '],
  	    	  
         	
    	     		['TVM Schoolhouse', '44.3071949', '-78.3280039',1,'<h4>TVM Schoolhouse, ON</h4><a href ="http://tvmgroup.onroad.org/residential/tvm-schoolhouse/">More Info</a>', 'bachelor one two '],
  	    	  
         	
    	     		['TVM Terraces', '44.306868', '-78.328013',1,'<h4>TVM Terraces, ON</h4><a href ="http://tvmgroup.onroad.org/residential/tvm-terraces/">More Info</a>', 'two three '],
  	    	  
         	
    	     		['TVM George St.', '44.308311', '-78.322177',1,'<h4>TVM George St., ON</h4><a href ="http://tvmgroup.onroad.org/residential/tvm-george-st/">More Info</a>', 'bachelor one two '],
  	    	  
         	
    	     		['TVM Mansions', '44.30653', '-78.328078',1,'<h4>TVM Mansions, ON</h4><a href ="http://tvmgroup.onroad.org/residential/tvm-mansions/">More Info</a>', 'bachelor one two three '],
  	    	  
         	
    	     		['TVM Hunter', '44.3057949', '-78.3221051',1,'<h4>TVM Hunter, ON</h4><a href ="http://tvmgroup.onroad.org/residential/tvm-hunter/">More Info</a>', 'bachelor one two '],
  	    	  
         	
    	     		['TVM Courtyard', '44.278497', '-78.374222',1,'<h4>TVM Courtyard, ON</h4><a href ="http://tvmgroup.onroad.org/residential/tvm-courtyard/">More Info</a>', 'two three '],
  	    	  
         
    ];
	var init = "";
	var gmarkers = [];
     var iterator = 1;

	var image = 'http://tvmgroup.onroad.org/wp-content/themes/tvm/images/mapicon.png';
    function setMarkers(map, markers) {

        for (var i = 0; i < markers.length; i++) {
       // alert(markers.length);
            var sites = markers[i];
            var siteLatLng = new google.maps.LatLng(sites[1], sites[2]);
            var marker = new google.maps.Marker({
                position: siteLatLng,
                map: map,
                icon: 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld='+(i+1)+'|000000|ffffff',
                animation: google.maps.Animation.DROP,
                title: sites[0],
                zIndex: sites[3],
                html: sites[4]
            });
            marker.mycategory = sites[5]; 
            gmarkers.push(marker);
            //marker.metadata = {type: "point", id: "1"};

            var contentString = "Some content";

            google.maps.event.addListener(marker, "click", function () {
               // alert(this.html);
                infowindow.setContent(this.html);
                infowindow.open(map, this);
            });
        }
        
    }
 // == shows all markers of a particular category, and ensures the checkbox is checked ==
      function show(category) {
      //	alert(category);
      
        for (var i=0; i<gmarkers.length; i++) {
       // alert(gmarkers[i].mycategory);
       	  if (category.indexOf( "all" ) !== -1) {
       	  	gmarkers[i].setVisible(true);
       	  }
          else if (gmarkers[i].mycategory.indexOf( category ) !== -1) {
            gmarkers[i].setVisible(true);
          } else{
          	gmarkers[i].setVisible(false);
          }
        }
        // == check the checkbox ==
        //document.getElementById(category+"box").checked = true;
      }

      // == hides all markers of a particular category, and ensures the checkbox is cleared ==
      function hide(category) {
        for (var i=0; i<gmarkers.length; i++) {
          if (gmarkers[i].mycategory == category) {
            gmarkers[i].setVisible(false);
          }
        }
        // == clear the checkbox ==
        //document.getElementById(category+"box").checked = false;
        // == close the info window, in case its open on a marker that we just hid
        infowindow.close();
      }

      // == a checkbox has been clicked ==
     

google.maps.event.addDomListener(window, 'load', initialize);


	$(function() {
		
		
$('.bluebox').click(function() {
			$('.bluebox').addClass('off');
			$(this).removeClass('off');
			var cat = $(this).attr("id");
			show(cat);
			
			});

	});

Open in new window

0
m2ew
Asked:
m2ew
  • 3
  • 3
1 Solution
 
Tom BeckCommented:
I have no way to properly test this without the rest of your markup and css, but it seems you could just call setMarkers again after running show or hide. Inside show and hide you create a subset of the sites array and pass it into setMarkers. Inside setMarkers, set the bounds of the new map based on the visible markers and zoom the map to fit the new bounds.  Something like this:
var init = "";
	var gmarkers = [];
     var iterator = 1;

	var image = 'http://tvmgroup.onroad.org/wp-content/themes/tvm/images/mapicon.png';
    function setMarkers(map, markers) {

        for (var i = 0; i < markers.length; i++) {
       // alert(markers.length);
            var sites = markers[i];
            var siteLatLng = new google.maps.LatLng(sites[1], sites[2]);
		    var bounds = new google.maps.LatLngBounds ();
			bounds.extend(siteLatLng);
            var marker = new google.maps.Marker({
                position: siteLatLng,
                map: map,
                icon: 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld='+(i+1)+'|000000|ffffff',
                animation: google.maps.Animation.DROP,
                title: sites[0],
                zIndex: sites[3],
                html: sites[4]
            });
            //marker.metadata = {type: "point", id: "1"};

            var contentString = "Some content";

            google.maps.event.addListener(marker, "click", function () {
               // alert(this.html);
                infowindow.setContent(this.html);
                infowindow.open(map, this);
            });
        }
        map.fitBounds(bounds);
    }
// == shows all markers of a particular category, and ensures the checkbox is checked ==
	  var sitesSubset = [];
      function show(category) {
      //	alert(category);
      
        for (var i=0; i<sites.length; i++) {
       // alert(gmarkers[i].mycategory);
       	  if (category.indexOf( "all" ) !== -1) {
			sitesSubset.push(sites[i]);
       	  }
          else if (sites[i][5].indexOf( category ) !== -1) {
			sitesSubset.push(sites[i]);
          } 
        }
		setMarkers(map, sitesSubset);
        // == check the checkbox ==
        //document.getElementById(category+"box").checked = true;
      }

      // == hides all markers of a particular category, and ensures the checkbox is cleared ==
      function hide(category) {
        for (var i=0; i<sites.length; i++) {
          if (sites[i][5] != category) {
			sitesSubset.push(sites[i]);
		  }
        }
		setMarkers(map, sitesSubset);
        // == clear the checkbox ==
        //document.getElementById(category+"box").checked = false;
        // == close the info window, in case its open on a marker that we just hid
        infowindow.close();
      }

Open in new window

0
 
m2ewAuthor Commented:
That seems like it should work. fitToBounds is coming up undefined though.
The test page is here http://tvmgroup.onroad.org/peterborough-apartments-for-rent/

I was reworking last night and kept coming across the same error.

function setMarkers(map, markers) {
var bounds = new google.maps.LatLngBounds ();
        for (var i = 0; i < markers.length; i++) {
       // alert(markers.length);
            var sites = markers[i];
            var siteLatLng = new google.maps.LatLng(sites[1], sites[2]);
		    
			bounds.extend(siteLatLng);
            var marker = new google.maps.Marker({
                position: siteLatLng,
                map: map,
                icon: 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld='+(i+1)+'|000000|ffffff',
                animation: google.maps.Animation.DROP,
                title: sites[0],
                zIndex: sites[3],
                html: sites[4]
            });
            //marker.metadata = {type: "point", id: "1"};

            var contentString = "Some content";

            google.maps.event.addListener(marker, "click", function () {
               // alert(this.html);
                infowindow.setContent(this.html);
                infowindow.open(map, this);
            });
        }
        map.fitBounds(bounds);
    }

Open in new window

0
 
Tom BeckCommented:
I extracted the key elements from your site and created a new page for testing. I modified the code I provided earlier to include a function to remove markers. You have a hide function but it never gets called. I don't think you need it. When I click the links on the test page, the subset of markers drop and the map is re-centered and zoomed to fit all markers. Here's the whole test page. Be sure to add your google maps key.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
	<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=YOUR_KEY_HERE&sensor=false"></script>
<style type="text/css">
		#map_canvaswrap{
			background: url(http://tvmgroup.onroad.org/wp-content/themes/tvm/images/map-canvas-contact.gif) no-repeat;
			padding: 7px 0 7px 6px;
		}
      #map_canvas {
        height: 446px;
width: 666px;

        border: none;
               /*  margin-top: 0.6em; */
      }
	  #secondary {
    float: right;
    padding-top: 14px;
    width: 290px;
}
.widget {
    clear: both;
    margin: 0 0 2.2em;
}
    </style>
</head>

<body><div class="entry-content">
		<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places&amp;sensor=false"></script>
	
		
   <script type="text/javascript">
      
	var map;
  function initialize() {
		
        var centerMap = new google.maps.LatLng(44.3019727, -78.3539062);

        var myOptions = {
            zoom:14,
            center: centerMap,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
        }

        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

        setMarkers(map, sites);
	    infowindow = new google.maps.InfoWindow({
                content: "loading…"
            });

      
    }

  var sites = [
    
         	
    	     		['TVM Apartments', '44.278509', '-78.3742282',1,'<h4>TVM Apartments, ON</h4><a href ="http://tvmgroup.onroad.org/residential/tvm-apartments/">More Info</a>', 'two three '],
  	    	  
         	
    	     		['TVM Manor', '44.309494', '-78.325782',1,'<h4>TVM Manor, ON</h4><a href ="http://tvmgroup.onroad.org/residential/tvm-manor/">More Info</a>', 'one two '],
  	    	  
         	
    	     		['TVM Tower Residences', '44.3070732', '-78.3225406',1,'<h4>TVM Tower Residences, ON</h4><a href ="http://tvmgroup.onroad.org/residential/tvm-tower-residences/">More Info</a>', 'one two three '],
  	    	  
         	
    	     		['TVM Peterborough', '44.3071462', '-78.3204109',1,'<h4>TVM Peterborough, ON</h4><a href ="http://tvmgroup.onroad.org/residential/tvm-peterborough/">More Info</a>', 'bachelor one two '],
  	    	  
         	
    	     		['TVM Schoolhouse', '44.3071949', '-78.3280039',1,'<h4>TVM Schoolhouse, ON</h4><a href ="http://tvmgroup.onroad.org/residential/tvm-schoolhouse/">More Info</a>', 'bachelor one two '],
  	    	  
         	
    	     		['TVM Terraces', '44.306868', '-78.328013',1,'<h4>TVM Terraces, ON</h4><a href ="http://tvmgroup.onroad.org/residential/tvm-terraces/">More Info</a>', 'two three '],
  	    	  
         	
    	     		['TVM George St.', '44.308311', '-78.322177',1,'<h4>TVM George St., ON</h4><a href ="http://tvmgroup.onroad.org/residential/tvm-george-st/">More Info</a>', 'bachelor one two '],
  	    	  
         	
    	     		['TVM Mansions', '44.30653', '-78.328078',1,'<h4>TVM Mansions, ON</h4><a href ="http://tvmgroup.onroad.org/residential/tvm-mansions/">More Info</a>', 'bachelor one two three '],
  	    	  
         	
    	     		['TVM Hunter', '44.3057949', '-78.3221051',1,'<h4>TVM Hunter, ON</h4><a href ="http://tvmgroup.onroad.org/residential/tvm-hunter/">More Info</a>', 'bachelor one two '],
  	    	  
         	
    	     		['TVM Courtyard', '44.278497', '-78.374222',1,'<h4>TVM Courtyard, ON</h4><a href ="http://tvmgroup.onroad.org/residential/tvm-courtyard/">More Info</a>', 'two three '],
  	    	  
         
    ];
	var init = "";
	var gmarkers = [];
     var iterator = 1;

	var image = 'http://tvmgroup.onroad.org/wp-content/themes/tvm/images/mapicon.png';
    function setMarkers(map, markers) {
		clearOverlays();
		 var bounds = new google.maps.LatLngBounds ();
        for (var i = 0; i < markers.length; i++) {
       // alert(markers.length);
            var sites = markers[i];
            var siteLatLng = new google.maps.LatLng(sites[1], sites[2]);
		   
			bounds.extend(siteLatLng);
            var marker = new google.maps.Marker({
                position: siteLatLng,
                map: map,
                icon: 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld='+(i+1)+'|000000|ffffff',
                animation: google.maps.Animation.DROP,
                title: sites[0],
                zIndex: sites[3],
                html: sites[4]
            });
            //marker.metadata = {type: "point", id: "1"};
			gmarkers.push(marker);
            var contentString = "Some content";

            google.maps.event.addListener(marker, "click", function () {
               // alert(this.html);
                infowindow.setContent(this.html);
                infowindow.open(map, this);
            });
        }
        map.fitBounds(bounds);
    }
	function clearOverlays() {
		if(gmarkers.length > 0){
  			for (var i = 0; i < gmarkers.length; i++ ) {
    			gmarkers[i].setMap(null);
  			}
		}
	}
// == shows all markers of a particular category, and ensures the checkbox is checked ==
      function show(category) {
      //	alert(category);
      
	    var sitesSubset = [];
        for (var i=0; i<sites.length; i++) {
       // alert(gmarkers[i].mycategory);
       	  if (category.indexOf( "all" ) !== -1) {
			sitesSubset.push(sites[i]);
       	  }
          else if (sites[i][5].indexOf( category ) !== -1) {
			sitesSubset.push(sites[i]);
          } 
        }
		setMarkers(map, sitesSubset);
        // == check the checkbox ==
        //document.getElementById(category+"box").checked = true;
      }

      // == hides all markers of a particular category, and ensures the checkbox is cleared ==
      function hide(category) {
		  
	    var sitesSubset = [];
        for (var i=0; i<sites.length; i++) {
          if (sites[i][5] != category) {
			sitesSubset.push(sites[i]);
		  }
        }
		setMarkers(map, sitesSubset);
        // == clear the checkbox ==
        //document.getElementById(category+"box").checked = false;
        // == close the info window, in case its open on a marker that we just hid
        infowindow.close();
      }     

google.maps.event.addDomListener(window, 'load', initialize);


	$(function() {
		
		
$('.bluebox').click(function() {
			$('.bluebox').addClass('off');
			$(this).removeClass('off');
			var cat = $(this).attr("id");
			show(cat);
			
			});

	});


			
    </script>
    <div id="map_canvaswrap">
    	<div id="map_canvas"></div>
	</div>
					</div><!-- .entry-content -->
                    <div id="secondary" class="widget-area" role="complementary">
			<aside id="archives" class="widget city">
			<h2 class="entry-title">Bedrooms</h2>
	
		<div class="itemwrap">
            <a href="javascript:;"><div class="bluebox lg" id="all">ALL</div></a> 
            <a href="javascript:;"><div class="bluebox off" id="bachelor">B</div></a>
            <a href="javascript:;"><div class="bluebox off" id="one">1</div></a> 
            <a href="javascript:;"><div class="bluebox off" id="two">2</div></a> 
            <a href="javascript:;"><div class="bluebox off" id="three">3+</div></a>
			<span class="rentrange">Rent from $472 - $1275</span></div>					</aside>
		</div><!-- #secondary .widget-area -->
</body>
</html>

Open in new window

0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
m2ewAuthor Commented:
Brilliant. This works perfect. I dumped the hide function as its isn't required
0
 
m2ewAuthor Commented:
Excellent solution and explanation of code revision.
0
 
Tom BeckCommented:
Glad it worked for you. Thanks for the points and kudos.
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 3
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now