?
Solved

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

Posted on 2012-09-20
10
Medium Priority
?
1,781 Views
Last Modified: 2012-09-21
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

0
Comment
Question by:m2ew
  • 5
  • 5
10 Comments
 
LVL 38

Expert Comment

by:Tom Beck
ID: 38420552
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
 

Author Comment

by:m2ew
ID: 38421825
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
 
LVL 38

Expert Comment

by:Tom Beck
ID: 38422766
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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 

Author Comment

by:m2ew
ID: 38422953
@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
 
LVL 38

Accepted Solution

by:
Tom Beck earned 2000 total points
ID: 38423127
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
 

Author Comment

by:m2ew
ID: 38423227
@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
 

Author Comment

by:m2ew
ID: 38423302
@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
 
LVL 38

Assisted Solution

by:Tom Beck
Tom Beck earned 2000 total points
ID: 38423842
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
 

Author Closing Comment

by:m2ew
ID: 38423953
Moving the service setting did the trick. Thanks for the great solution @tommyBoy
0
 
LVL 38

Expert Comment

by:Tom Beck
ID: 38423986
You're welcome. Thanks for the points.
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

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

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Today, the web development industry is booming, and many people consider it to be their vocation. The question you may be asking yourself is – how do I become a web developer?
When it comes to security, close monitoring is a must. According to WhiteHat Security annual report, a substantial number of all web applications are vulnerable always. Monitis offers a new product - fully-featured Website security monitoring and pr…
This tutorial walks through the best practices in adding a local business to Google Maps including how to properly search for duplicates, marker placement, and inputing business details. Login to your Google Account, then search for "Google Mapmaker…
The viewer will learn how to dynamically set the form action using jQuery.
Suggested Courses
Course of the Month16 days, 3 hours left to enroll

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question