www.webdeveloper.com
Results 1 to 2 of 2

Thread: Filter Google Maps Markers On Selecteion

  1. #1
    Join Date
    Jun 2013
    Posts
    6

    Filter Google Maps Markers On Selecteion

    Hi there,

    I posted earlier on how to get data out of a database and plot it on a map. I managed to do so by using PHP to get the data from the db, export the data as an xml file (more like a variable, it doesn't make a physical file) and then letting the javascript read the xml.

    I have a database called google and a table called markers. The SQL for the data in the database is:
    Code:
    INSERT INTO `markers` (`name`, `address`, `lat`, `lng`, `type`) VALUES ('Pan Africa Market', '1521 1st Ave, Seattle, WA', '47.608941', '-122.340145', 'restaurant');
    INSERT INTO `markers` (`name`, `address`, `lat`, `lng`, `type`) VALUES ('Buddha Thai & Bar', '2222 2nd Ave, Seattle, WA', '47.613591', '-122.344394', 'bar');
    INSERT INTO `markers` (`name`, `address`, `lat`, `lng`, `type`) VALUES ('The Melting Pot', '14 Mercer St, Seattle, WA', '47.624562', '-122.356442', 'restaurant');
    INSERT INTO `markers` (`name`, `address`, `lat`, `lng`, `type`) VALUES ('Ipanema Grill', '1225 1st Ave, Seattle, WA', '47.606366', '-122.337656', 'restaurant');
    INSERT INTO `markers` (`name`, `address`, `lat`, `lng`, `type`) VALUES ('Sake House', '2230 1st Ave, Seattle, WA', '47.612825', '-122.34567', 'bar');
    INSERT INTO `markers` (`name`, `address`, `lat`, `lng`, `type`) VALUES ('Crab Pot', '1301 Alaskan Way, Seattle, WA', '47.605961', '-122.34036', 'restaurant');
    INSERT INTO `markers` (`name`, `address`, `lat`, `lng`, `type`) VALUES ('Mama\'s Mexican Kitchen', '2234 2nd Ave, Seattle, WA', '47.613975', '-122.345467', 'bar');
    INSERT INTO `markers` (`name`, `address`, `lat`, `lng`, `type`) VALUES ('Wingdome', '1416 E Olive Way, Seattle, WA', '47.617215', '-122.326584', 'bar');
    INSERT INTO `markers` (`name`, `address`, `lat`, `lng`, `type`) VALUES ('Piroshky Piroshky', '1908 Pike pl, Seattle, WA', '47.610127', '-122.342838', 'restaurant');
    So basically the info looks like this:
    Code:
    Pan Africa Market,"1521 1st Ave, Seattle, WA",47.608941,-122.340145,restaurant
    Buddha Thai & Bar,"2222 2nd Ave, Seattle, WA",47.613591,-122.344394,bar
    The Melting Pot,"14 Mercer St, Seattle, WA",47.624562,-122.356442,restaurant
    Ipanema Grill,"1225 1st Ave, Seattle, WA",47.606366,-122.337656,restaurant
    Sake House,"2230 1st Ave, Seattle, WA",47.612825,-122.34567,bar
    Crab Pot,"1301 Alaskan Way, Seattle, WA",47.605961,-122.34036,restaurant
    Mama's Mexican Kitchen,"2234 2nd Ave, Seattle, WA",47.613975,-122.345467,bar
    Wingdome,"1416 E Olive Way, Seattle, WA",47.617215,-122.326584,bar
    Piroshky Piroshky,"1908 Pike pl, Seattle, WA",47.610127,-122.342838,restaurant
    Then I have 3 files, the database info, the file to generate the xml and the map page itself. The code is as follows...

    dbinfo.php (database information) :
    Code:
    <?php
    	$username="root";
    	$password="";
    	$database="google";
    ?>
    genxml3.php (XML generator from database table) :
    Code:
    <?php  
    
    require("dbinfo.php"); 
    
    // Start XML file, create parent node
    
    $dom = new DOMDocument("1.0");
    $node = $dom->createElement("markers");
    $parnode = $dom->appendChild($node); 
    
    // Opens a connection to a MySQL server
    
    $connection=mysql_connect('localhost', $username, $password);
    if (!$connection) {  die('Not connected : ' . mysql_error());} 
    
    // Set the active MySQL database
    
    $db_selected = mysql_select_db($database, $connection);
    if (!$db_selected) {
      die ('Can\'t use db : ' . mysql_error());
    } 
    
    // Select all the rows in the markers table
    
    $query = "SELECT * FROM markers WHERE 1";
    $result = mysql_query($query);
    if (!$result) {  
      die('Invalid query: ' . mysql_error());
    } 
    
    header("Content-type: text/xml"); 
    
    // Iterate through the rows, adding XML nodes for each
    
    while ($row = @mysql_fetch_assoc($result)){  
      // ADD TO XML DOCUMENT NODE  
      $node = $dom->createElement("marker");  
      $newnode = $parnode->appendChild($node);   
      $newnode->setAttribute("name",$row['name']);
      $newnode->setAttribute("address", $row['address']);  
      $newnode->setAttribute("lat", $row['lat']);  
      $newnode->setAttribute("lng", $row['lng']);  
      $newnode->setAttribute("type", $row['type']);
    } 
    
    echo $dom->saveXML();
    
    ?>
    and finally my html file map.html:
    Code:
    <!doctype html>
    <html>
    	<head>
    		<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    		<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    		<title>PHP & Google Maps</title>
    		<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyASO80RjNn2d_Jjy9vdNHA5E3tfmALkWXw&sensor=false"></script>
    		<script type="text/javascript">
    			
    			//<![CDATA[
    			
    			var customIcons = {
    				restaurant: {
    					icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png',
    					shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
    				},
    				bar: {
    					icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png',
    					shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
    				}
    			};
    			
    			function load() {
    				var map = new google.maps.Map(document.getElementById("map"), {
    					center: new google.maps.LatLng(47.6145, -122.3418),
    					zoom: 13,
    					mapTypeId: 'roadmap',
    					disableDefaultUI: true
    				});
    				var infoWindow = new google.maps.InfoWindow;
    				
    				// Change this depending on the name of your PHP file
    				downloadUrl("genxml3.php", function(data) {
    					var xml = data.responseXML;
    					var markers = xml.documentElement.getElementsByTagName("marker");
    					for (var i = 0; i < markers.length; i++) {
    						var name = markers[i].getAttribute("name");
    						var address = markers[i].getAttribute("address");
    						var type = markers[i].getAttribute("type");
    						var point = new google.maps.LatLng(
    							parseFloat(markers[i].getAttribute("lat")),
    							parseFloat(markers[i].getAttribute("lng"))
    						);
    						var html = "<b>" + name + "</b> <br />" + address + "<br />" + type;
    						var icon = customIcons[type] || {};
    						var marker = new google.maps.Marker({
    							map: map,
    							position: point,
    							icon: icon.icon,
    							shadow: icon.shadow
    						});
    						bindInfoWindow(marker, map, infoWindow, html);
    					}
    				});
    				
    				downloadUrl2("genxml3.php", function(data) {
    					var xml = data.responseXML;
    					var markers = xml.documentElement.getElementsByTagName("marker");
    					for (var i = 0; i < markers.length; i++) {
    						var name = markers[i].getAttribute("name");
    						var address = markers[i].getAttribute("address");
    						var type = markers[i].getAttribute("type");
    						var point = new google.maps.LatLng(
    							parseFloat(markers[i].getAttribute("lat")),
    							parseFloat(markers[i].getAttribute("lng"))
    						);
    						var html = "<b>" + name + "</b> <br />" + address + "<br />" + type;
    						var icon = customIcons[type] || {};
    						var marker = new google.maps.Marker({
    							map: map,
    							position: point,
    							icon: icon.icon,
    							shadow: icon.shadow
    						});
    						bindInfoWindow(marker, map, infoWindow, html);
    					}
    				});
    			}
    			
    			function bindInfoWindow(marker, map, infoWindow, html){
    				google.maps.event.addListener(marker, 'click', function(){
    					infoWindow.setContent(html);
    					infoWindow.open(map, marker);
    				});
    			}
    			
    			function downloadUrl(url, callback) {
    				var request = window.ActiveXObject ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest;
    				
    				request.onreadystatechange = function() {
    					if (request.readyState == 4) {
    						request.onreadystatechange = doNothing;
    						callback(request, request.status);
    					}
    				};
    				
    				request.open('GET', url, true);
    				request.send(null);
    			}
    			
    			function doNothing() {}
    			
    			//]]>
    			
    			
    		</script>
    	</head>
    	<body onload="load()">
    		<div id="map" style="width:500px;height:380px;"></div>
    		<ul>
    			<li><a href="#">restaurant</a></li>
    			<li><a href="#">bar</a></li>
    		</ul>
    	</body>
    </html>
    Now I need to build a "filter/search" feature for it by type.

    There are 2 types in this example, a bar and a restaurant. I need to be able to click on restaurant and only the markers with type restaurant will show, and if bar is selected, only type bar will show.

    I tried forcing the links to have a 'get' variable and try pick it up in PHP:
    Code:
    <li><a href="map.html?filter=restaurant">restaurant</a></li>
    and then in php:
    Code:
    if(!empty($_GET)){
    	
    	$filter = $_GET['f'];
    	$query = "SELECT * FROM markers WHERE type = '$filter'";
    	$result = mysql_query($query);
    	if (!$result) {  
    		die('Invalid query: ' . mysql_error());
    	}
    	
    } else {
    	$query = "SELECT * FROM markers WHERE 1";
    	$result = mysql_query($query);
    	if (!$result) {  
    		die('Invalid query: ' . mysql_error());
    	}
    }
    Which when I run the genxml3.php file, gives me an xml file that has only type restaurant in it, no type bar, which is EXACTLY what I want, but then the map doesn't recognize the change and still displays both type restaurant and bar.

    How can I force the JavaScript to change when a link is pressed? how can I get the JavaScript to run the PHP file with the 'get' variable and only output the type specified?

    Alternately, How else can I build in a search feature?

    Any other ideas?

    Thank you in advance,
    Josh.

    P.s: Incase you didn't realize, the code I used is from https://developers.google.com/maps/a.../phpsqlajax_v3.

  2. #2
    Join Date
    Nov 2010
    Posts
    978
    the dumb way:
    every time someone makes a new search, clear the entire map and request those markers matching the search query from your database

    the smart way:
    on page load, push all of your markers into an array. Whenever a new search query is issued, loop through those markers, hiding the ones that don't match and showing the ones that do.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles