More Examples

Adding and deleting markers, changing marker colors, re-setting bounds

marker color:


<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Adding and deleting markers, changing marker colors, re-setting bounds</title>

     <style type="text/css">
          
		#map-canvas {
		   width: 600px;
		   height: 400px;
		   border: 10px;
		   margin: 10px;
		}
		pre {
			border:1px solid #D6E0F5;
			padding:5px;
			margin:5px;
			background:#EBF0FA;
		}	
		#panel {
		   z-index: 5;
		   background-color: #fff;
		   padding: 5px;
		}          
		table {
		   border-collapse: collapse;
		}
		td{ border: 1px solid #B0B0B0;
			padding: 5px;
			background-color: #F8F8F8 ;               
			vertical-align:top;
		}          		
		button{
			width:100%;
			height: 60px;
		}

     </style>
     
     <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
     <script src="../jquery/jquery.js" type="text/javascript"></script>     
     
     <script src='color-picker/spectrum.js'></script>
     <link rel='stylesheet' href='color-picker/spectrum.css' />          
     <script type="text/javascript">

	"use strict"     
	
     $( document ).ready(function() {
          
		var map;
		var myMarkers = []; 
		var count = 0;
		var markerColor = '#f00000';			// default colour
		var userZoom = false;					// did user request zoom

		// -----------------------------------------------
		// function initialize
		// -----------------------------------------------
			function initialize() {
				var mapCenter = new google.maps.LatLng(45.504 , -73.597);
				var mapOptions = {
				   zoom: 10,
				   center: mapCenter,
				   mapTypeId: google.maps.MapTypeId.TERRAIN
				};
				map = new google.maps.Map(document.getElementById('map-canvas'),
					 mapOptions);

				// This event listener will call addMarker() when the map is clicked.
				google.maps.event.addListener(map, 'click', function(evt) {
						addMarker(evt.latLng);
						var textToInsert = '';     
						var myLat = evt.latLng.lat().toFixed(5)
						var myLng = evt.latLng.lng().toFixed(5)
						textToInsert = '<tr  class="deleteRow" ><td>' + count++ + '</td><td>' + myLat + '</td><td  class="deleteOneMarker">' + myLng + '</td><td class="deleteOneMarker"><a href="#" ><img  src="img/delete.png"></a></td></tr>';               
						$('#myTable').append(textToInsert);                                                            
					 });
				
				//----------------------------------------------------------------------          
				// LISTENER:  add event on map's zoom level change 
				//----------------------------------------------------------------------			
				google.maps.event.addListener(map, "zoom_changed", function() {					
					// determine who asked for zoom
					if (userZoom == true){				   
					   if (map.getZoom() > 8) {
						 map.setZoom(8);
						 // set back to default of false
						 userZoom = false;
					   }
					}
				}); 
				
				
				
				
							
			}  // end initialize
			// -----------------------------------------------
			// FUNCTION - add marker on click
			// -----------------------------------------------
			function addMarker(position) {
			 var marker = new google.maps.Marker( {            
				position: position,
				icon: {
				  path: google.maps.SymbolPath.CIRCLE,
				  scale: 5,
				  strokeColor: markerColor
				},
				map: map
				
			 });
			 // pan to position
			 map.panTo(position);

			 myMarkers.push(marker);
			 
			} // end - add marker 
					               
			// -----------------------------------------------
			// FUNCTION - Sets the map on all markers in the array.
			// -----------------------------------------------
			function setAllMap(map) {
				for (var i = 0; i < myMarkers.length; i++) {
				   myMarkers[i].setMap(map);
				}
			}

			// -----------------------------------------------
			// function fnSetBounds : resets bounds of map
			// -----------------------------------------------
			function fnSetBounds(){		  

				if (myMarkers.length < 1){
					alert("You cannot fit all markers on the page unless you have added at least one marker!");
					return;
				}

				var bounds = new google.maps.LatLngBounds();
				for (var i = 0; i < myMarkers.length; i++) {
					if (!myMarkers[i] ) continue;
					bounds.extend(myMarkers[i].getPosition());
				}                   
				map.fitBounds(bounds);
			};
			
			// -----------------------------------------------
			// function fnSetBoundsWithMinimumZoomLevel : resets bounds of map
			// -----------------------------------------------
			function fnSetBoundsWithMinimumZoomLevel(){		  

				if (myMarkers.length < 1){
					alert("You cannot fit all markers on the page unless you have added at least one marker!");
					return;
				}

				// user requested zoom
				userZoom = true;
				var bounds = new google.maps.LatLngBounds();
				for (var i = 0; i < myMarkers.length; i++) {
					if (!myMarkers[i] ) continue;
					bounds.extend(myMarkers[i].getPosition());
				}                   
				map.fitBounds(bounds);
			};
			
			// -------------------------------------------------------------------		
			// tear down and re-build html table after delete
			// -------------------------------------------------------------------		  
			function fnReDrawTable(){
			   var textToInsert = '';     
			   $("table#myTable").find("tr").remove();                                             
			   for (var i = 0; i < myMarkers.length; i++) {                                        
					if (myMarkers[i] != null){                         
						 console.log("i");
						 var myLat = myMarkers[i].position.lat().toFixed(5)
						 var myLng = myMarkers[i].position.lng().toFixed(5)                    
						 textToInsert = '<tr  class="deleteRow" ><td>' + i + '</td><td>' + myLat + '</td><td  class="deleteOneMarker">' + myLng + '</td><td class="deleteOneMarker"><a href="#" ><img  src="img/delete.png"></a></td></tr>';               
						 $('#myTable').append(textToInsert);
						 
						 }
					}
			}

			//----------------------------------------------------------------------          
			// LISTENER: on delete row in table
			//----------------------------------------------------------------------			
			$('#myTable').on('click', '.deleteRow', function(evt) {                              
			   var myIndex =  $(this).closest('tr').find('td:first').text();			   
			   // make marker disappear on map
			   myMarkers[myIndex].setMap(null);
			   myMarkers[myIndex] = null;		   
			   // delete all in table
			   fnReDrawTable();
			});

			//----------------------------------------------------------------------          
			// LISTENER: on Fit Bounds button
			//----------------------------------------------------------------------			
			$('#btnFitBounds').on('click', function(evt) {                              			   
			   fnSetBounds();			   
			});
			
			//----------------------------------------------------------------------          
			// LISTENER: on Fit Bounds button - minimum zoom level 
			//----------------------------------------------------------------------			
			$('#btnFitBoundsWithMinimumZoomLevel').on('click', function(evt) {                              			   			   
			   fnSetBoundsWithMinimumZoomLevel();
			});


			//----------------------------------------------------------------------          
			// color picker setup
			//----------------------------------------------------------------------			
			$(".basic").spectrum({
				color: "#f00",
				change: function(color) {
					$("#basic-log").text("new color: " + color.toHexString());
					markerColor = color.toHexString();		

				}
			});  // end color picker setup

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

  </script>
  </head>
  <body>
    <div id="panel">
      <!-- <input id='clear' type=button value="Hide Markers">
      <input id='show' type=button value="Show All Markers">
      <input id='delete' type=button value="Delete Markers">  -->
       
    </div>
	<a href="../index.php">BACK</a> <br/>   
	<h4>Adding and deleting markers, changing marker colors, re-setting bounds</h4>
	<ul>
		<li>click on the map to add marker</li>
		<li>reset map boundaries ("fit bounds")</li>
		<li>change marker color</li>
	</ul>
	<table>
		<tr><td>
			<div id="map-canvas"></div>
		</td><td style='vertical-align:top;' width=30%>
			<em>marker color:</em> <input type='text' class='basic' name='colorPicker' />	   
			<br/><br/>
			<table id='myTable'>
			</table>
			<br/>
			<button id='btnFitBounds'>Fit Bounds</button>
			<button id='btnFitBoundsWithMinimumZoomLevel'>Fit Bounds with minimum<br/> zoom level</button>
		</td></tr>	
	</table>