Google Maps API v3 - Drop Google Places Markers while having a static marker.

I'm using google places to add my markers for amenities. I have of default of 'school' as the value.

How do I add a separate marker (which is the centerMap var) so its always static; even when I clear out / refresh the places markers. I have a template map here at http://tvmgroup.onroad.org/residential/37tvm-king-st/

 <script type="text/javascript">
            var map;
      var infowindow;
		var category;
      function initialize(category) {
        var centerMap = new google.maps.LatLng(43.9593373, -78.1677363);

        map = new google.maps.Map(document.getElementById('map_canvas'), {
          mapTypeId: google.maps.MapTypeId.ROADMAP,
          center: centerMap,
          zoom: 15
        });
		if (category == "" || category == "[object Event]"){
			category = 'school'
		}
		alert(category);
        var request = {
          location: centerMap,
          radius: 500,
          types: [category]
        };
        infowindow = new google.maps.InfoWindow();
        var service = new google.maps.places.PlacesService(map);
        service.search(request, callback);
      }

      function callback(results, status) {
        if (status == google.maps.places.PlacesServiceStatus.OK) {
          for (var i = 0; i < results.length; i++) {
            createMarker(results[i]);
          }
        }
      }

      function createMarker(place) {
        var placeLoc = place.geometry.location;
        var marker = new google.maps.Marker({
          map: map,
          icon: 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=|000000|ffffff',
          position: place.geometry.location,
		  animation: google.maps.Animation.DROP
        });

        google.maps.event.addListener(marker, 'click', function() {
          infowindow.setContent(place.name);
          infowindow.open(map, this);
        });
      }

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

	$(function() {
		
		
$('.bluebox').click(function() {
			$('.bluebox').addClass('off');
			$('.bluebox').removeClass('on');
			$(this).removeClass('off');
			$(this).addClass('on');
			
			});

	});


			
    </script>

Open in new window

m2ewAsked:
Who is Participating?
 
Tom BeckCommented:
When you do a Google Places search, the coordinates are returned with the request so that part is easy. You just call geometry.location on the place. Anyway, here's a test page that does what you are trying to do.
<!DOCTYPE html>
<html>
<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 src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script> 
		<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places&amp;sensor=false"></script>
<script type="text/javascript">
        var init = "";
	var gmarkers = [];
	var image = 'http://tvmgroup.onroad.org/wp-content/themes/tvm/images/mapicon.png';
	var map;
	var centerMap;
    function initialize() {
	var category = "";
	centerMap  = new google.maps.LatLng(43.9593373, -78.1677363);
        var myOptions = {
            zoom:15,
            center: centerMap,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
        }

        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
		var staticMarker = new google.maps.Marker({
                position: centerMap,
                map: map,
                title:"Static Marker",
                icon: image,
                zIndex:1000
 	     });
	     if (category == ""){
		category = 'school'
	     }
		newCategory(category);
	    infowindow = new google.maps.InfoWindow({
                content: "loading…"
            });
		
         }
	function newCategory(category){
	      var request = {
                 location: centerMap,
                 radius: 500,
                 types: [category]
             };
	     var service = new google.maps.places.PlacesService(map);
             service.search(request, callback);
	}
        function setMarkers(results) {
	    clearOverlays();
            for (var i = 0; i < results.length; i++) {
                 createMarker(results[i]);
            }
        }
	function callback(results, status) {
           if (status == google.maps.places.PlacesServiceStatus.OK) {
		  setMarkers(results);
           }
        }
	function createMarker(place) {
           var placeLoc = place.geometry.location;
           var marker = new google.maps.Marker({
                map: map,
                position: placeLoc
           });
	   gmarkers.push(marker);
           google.maps.event.addListener(marker, 'click', function() {
              infowindow.setContent(place.name);
              infowindow.open(map, this);
           });
        }
	function clearOverlays() {
		if(gmarkers.length > 0){
  			for (var i = 0; i < gmarkers.length; i++ ) {
    			     gmarkers[i].setMap(null);
  			}
		}
	}

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

	$(function() {
		
		
$('#amenitiesmenu a div').click(function() {
			//$('.bluebox').addClass('off');
			$('#amenitiesmenu a div').removeClass('on');
			//$(this).removeClass('off');
			$(this).addClass('on');
			category = $(this).attr('id');
			newCategory(category);				 
			});

	});
</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; */
      }
    </style>
</head>

<body>
 <div id="map_canvaswrap">
    	<div id="map_canvas"></div>
	</div>
			<h2 class="entry-title">Places</h2>
	
		<div id="amenitiesmenu" class="itemwrap">
            <a href="javascript:;"><div class="bluebox lg" id="school">Schools</div></a> 
            <a href="javascript:;"><div class="bluebox off" id="restaurant">Restaurants</div></a>
		</div><!-- #secondary .widget-area -->
</body>
</html>

Open in new window

0
 
Tom BeckCommented:
You can include this in your initialize function to add a static marker.

          var staticMarker = new google.maps.Marker({
                position: centerMap,
                map: map,
                title:"Static Marker"
      });

I don't see in your code how you are clearing the places markers so I cannot address that directly, but generally you clear a marker by setting it's map to null: staticMarker.setMap(null) so to restore it you could use staticMarker.setMap(map).
0
 
m2ewAuthor Commented:
I adde the static marker as you stated and it worked great.
http://tvmgroup.onroad.org/residential/37tvm-king-st/

I've added a clearOvelays function but getting an error with results undefined; its not getting pushed correctly. Also, I need to re initialize the search for the new amenities, ie. parks which I was going to grab from the button id.

       var map;
      var infowindow;
		var category;
		var centerMap;
		var service;
		var gmarkers;
      function initialize(category) {
         centerMap = new google.maps.LatLng(43.9593373, -78.1677363);

        map = new google.maps.Map(document.getElementById('map_canvas'), {
          mapTypeId: google.maps.MapTypeId.ROADMAP,
          center: centerMap,
          zoom: 15
        });
		if (category == "" || category == "[object Event]"){
			category = 'school'
		}
		alert(category);
        var request = {
          location: centerMap,
          radius: 500,
          types: [category]
        };
        var image = 'http://tvmgroup.onroad.org/wp-content/themes/tvm/images/mapicon.png';
        var staticMarker = new google.maps.Marker({
                position: centerMap,
                map: map,
                title:"Static Marker",
                icon: image,
                zIndex:1000
 	     });
        infowindow = new google.maps.InfoWindow();
        var service = new google.maps.places.PlacesService(map);
        service.search(request, callback);
      }

      function callback(results, status) {
        if (status == google.maps.places.PlacesServiceStatus.OK) {
          for (var i = 0; i < results.length; i++) {
            createMarker(results[i]);
          }
          results.push(results[i]);
        }
      }

      function createMarker(place) {
        var placeLoc = place.geometry.location;
        var marker = new google.maps.Marker({
          map: map,
          icon: 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=|68afdb|ffffff',
          position: place.geometry.location,
		  animation: google.maps.Animation.DROP
        });
		//results.push(marker);

        google.maps.event.addListener(marker, 'click', function() {
          infowindow.setContent(place.name);
          infowindow.open(map, this);
        });
      }
	function clearOverlays() {
		if(results.length > 0){
  			for (var i = 0; i < results.length; i++ ) {
    			results[i].setMap(null);
  			}
		}
	}
      google.maps.event.addDomListener(window, 'load', initialize);

	$(function() {
		
		
$('#amenitiesmenu a div').click(function() {
			//$('.bluebox').addClass('off');
			$('#amenitiesmenu a div').removeClass('on');
			//$(this).removeClass('off');
			$(this).addClass('on');
			category = $(this).attr('id');
			clearOverlays();
				 
			});

	});

Open in new window

0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

 
Tom BeckCommented:
Deja vu.

We did something similar here:
http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Jquery/Q_27868480.html

The key was the setMarkers function which allowed you to clear and reset the markers when the links were clicked. You will need a similar setup for this situation.

Do you need help with that?
0
 
m2ewAuthor Commented:
@tommyBoy,
Yeah it is Deja Vu. I initial did try reworking that. The current version is more of a modification of the example I found on google maps API.

I tried integrating google places search (as I don't have the lat/long coords) into the setMarker  function, but was struggling reseting the search markers while keeping a static one.
0
 
m2ewAuthor Commented:
@tommyBoy thanks. this works great. I added the bounds function back in to recenter the page.

However, I'm noticing a bug where the Listings by yellowpages.ca keeps repeating.
http://tvmgroup.onroad.org/residential/37tvm-king-st/?newquery=1
0
 
m2ewAuthor Commented:
@tommyBoy here is the update javascript. I added bounds.extend(centerMap); so it would include the static marker. The only issue I'm having still is the Listings by yellowpages.ca repeat in the map window


   	     var init = "";
	var gmarkers = [];
	var image = 'http://tvmgroup.onroad.org/wp-content/themes/tvm/images/mapicon.png';
	var map;
	var centerMap;
	var bounds = new google.maps.LatLngBounds ();
    function initialize() {
	var category = "";
	centerMap  = new google.maps.LatLng(43.9593373, -78.1677363);
        var myOptions = {
            zoom:15,
            center: centerMap,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
        }

        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
		var staticMarker = new google.maps.Marker({
                position: centerMap,
                map: map,
                title:"Static Marker",
                icon: image,
                zIndex:1000
 	     });
	     if (category == ""){
		category = 'school'
	     }
		newCategory(category);
	    infowindow = new google.maps.InfoWindow({
                content: "loading…"
            });
		
         }
	function newCategory(category){
	      var request = {
                 location: centerMap,
                 radius: 1000,
                 types: [category]
             };
	     var service = new google.maps.places.PlacesService(map);
             service.search(request, callback);
	}
        function setMarkers(results) {
	    clearOverlays();
            for (var i = 0; i < results.length; i++) {
                 createMarker(results[i]);
            }
        }
	function callback(results, status) {
           if (status == google.maps.places.PlacesServiceStatus.OK) {
		  setMarkers(results);
           	
           }
        }
	function createMarker(place) {
		 
           var placeLoc = place.geometry.location;
		   	
			bounds.extend(placeLoc);
			bounds.extend(centerMap);
           var marker = new google.maps.Marker({
                map: map,
                position: placeLoc,
                 icon: 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=|68afdb|ffffff',
                 animation: google.maps.Animation.DROP
           });
	   gmarkers.push(marker);
           google.maps.event.addListener(marker, 'click', function() {
              infowindow.setContent(place.name);
              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);
  			}
		}
	}

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

	$(function() {
		
		
$('#amenitiesmenu a div').click(function() {
			$('#amenitiesmenu a div').removeClass('on');
			$(this).addClass('on');
			category = $(this).attr('id');
			newCategory(category);				 
			});

	});

Open in new window

0
 
Tom BeckCommented:
The "Listings by YellowPages.ca" is because we are recreating the Places service with each new category instead of re-using the same one. Simple fix.

Declare service as a global above the initialize function:

               var service;

Put this line (in bold) in your initialize function:

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

            service = new google.maps.places.PlacesService(map);

            var staticMarker = new google.maps.Marker({

Delete this line from the newCategory function:

                var service = new google.maps.places.PlacesService(map);
0
 
m2ewAuthor Commented:
Moving the service setting did the trick. Thanks for the great solution @tommyBoy
0
 
Tom BeckCommented:
You're welcome. Thanks for the points.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.