draw on google maps

Drawing on google maps

Dummy marker.sql


CREATE TABLE IF NOT EXISTS `markers` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(60) NOT NULL,
  `address` varchar(80) NOT NULL,
  `lat` float(10,6) NOT NULL,
  `lng` float(10,6) NOT NULL,
  `image` text NOT NULL,
  `type` varchar(125) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1  ;



INSERT INTO `markers` ( `name`, `address`, `lat`, `lng`, `image`, `type`) VALUES
( 'Pan Africa Market', '1521 1st Ave, Seattle, WA', 47.608940, -122.340141, 'http://photos2.zillowstatic.com/p_g/IS56cr7wy24v3i0000000000.jpg', 'restaurant'),
( 'Buddha Thai & Bar', '2222 2nd Ave, Seattle, WA', 47.613590, -122.344391, 'http://photos2.zillowstatic.com/p_g/IS56cr7wy24v3i0000000000.jpg', 'bar'),
( 'The Melting Pot', '14 Mercer St, Seattle, WA', 47.624561, -122.356445, 'http://photos2.zillowstatic.com/p_g/IS56cr7wy24v3i0000000000.jpg', 'restaurant'),
( 'Ipanema Grill', '1225 1st Ave, Seattle, WA', 47.606365, -122.337654, 'http://photos2.zillowstatic.com/p_g/IS56cr7wy24v3i0000000000.jpg', 'restaurant'),
( 'Sake House', '2230 1st Ave, Seattle, WA', 47.612823, -122.345673, 'http://photos2.zillowstatic.com/p_g/IS56cr7wy24v3i0000000000.jpg', 'bar'),
( 'Crab Pot', '1301 Alaskan Way, Seattle, WA', 47.605961, -122.340363, 'http://photos2.zillowstatic.com/p_g/IS56cr7wy24v3i0000000000.jpg', 'restaurant'),
( 'Mama''s Mexican Kitchen', '2234 2nd Ave, Seattle, WA', 47.613976, -122.345467, 'http://photos2.zillowstatic.com/p_g/IS56cr7wy24v3i0000000000.jpg', 'bar'),
( 'Wingdome', '1416 E Olive Way, Seattle, WA', 47.617214, -122.326584, 'http://photos2.zillowstatic.com/p_g/IS56cr7wy24v3i0000000000.jpg', 'bar'),
( 'Piroshky Piroshky', '1908 Pike pl, Seattle, WA', 47.610126, -122.342834, 'http://photos2.zillowstatic.com/p_g/IS56cr7wy24v3i0000000000.jpg', 'restaurant');


phpsqlajax_genxml.php


$username="ab";   //db username
$password="ab";    //db password
$database="ab";    // database name

$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("image", $row['image']);
  $newnode->setAttribute("type", $row['type']);
}

echo $dom->saveXML();

Maps.html


<script src="https://maps.googleapis.com/maps/api/js?key=GOOGLE_BROWSER_KEY_HERE&libraries=places,drawing,geometry"
            type="text/javascript"></script>
<script type="text/javascript">
var markers = [];
	var markersToRemove = [];
	var ploy;
	var customIcons = {
      restaurant: {
        icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png'
      },
      bar: {
        icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png'
      }
    };
    //function called on body load
    function load() {
      var map = new google.maps.Map(document.getElementById("map"), {
        center: new google.maps.LatLng(47.6145, -122.3418),
        zoom: 13,
        mapTypeId: 'roadmap'
      });
	  
	  
	  /****controlss *********************************/
	  
	  
	  var drawingManager = new google.maps.drawing.DrawingManager({
        drawingMode: google.maps.drawing.OverlayType.MARKER,
        drawingControl: true,
        drawingControlOptions: {
            position: google.maps.ControlPosition.TOP_CENTER,
            drawingModes: [
            google.maps.drawing.OverlayType.POLYGON,
            ]
        },
        markerOptions: {
            icon: 'images/beachflag.png'
        },
        circleOptions: {
            fillColor: '#ffff00',
            fillOpacity: 1,
            strokeWeight: 5,
            clickable: false,
            editable: true,
            zIndex: 1
        },
		
    });
    drawingManager.setMap(map);
	google.maps.event.addListener(drawingManager, 'overlaycomplete', function(event) {
		 for(var i = 0; i < markersToRemove.length; i++) {
			markersToRemove[i].setMap(null);
		}
		polyOptions  = event.overlay.getPath().getArray();   //get coordinates of polygon
		
		var poly = new google.maps.Polygon({
				paths : polyOptions,
				strokeColor: '#FF0000',
				strokeOpacity: 0.8,
				strokeWeight: 2,
				fillColor: '#FF0000',
				fillOpacity: 0.35,
				});  //get polygon using its coordinates
		downloadUrl("phpsqlajax_genxml.php", function(data) {
        var xml = data.responseXML;
        var markers = xml.documentElement.getElementsByTagName("marker");
		document.getElementById("content_list").innerHTML = "";
        for (var i = 0; i < markers.length; i++) {
                        //get our marker points from database
			var point = new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")),parseFloat(markers[i].getAttribute("lng")));
			console.log(google.maps.geometry.poly.containsLocation(point,poly));
			 if(google.maps.geometry.poly.containsLocation(point,poly)) { // check if marker point is inside polygon drawn
						var m = new google.maps.Marker({
							position: point,
							map: map
						});
						
						/************create list in sidebar again and render new list in sidebar*******/
						 var infoWin = new google.maps.InfoWindow;
						  var name = markers[i].getAttribute("name");
						  var address = markers[i].getAttribute("address");
						  var type = markers[i].getAttribute("type");
						  var image = markers[i].getAttribute("image");
						  var point = new google.maps.LatLng(
							  parseFloat(markers[i].getAttribute("lat")),
							  parseFloat(markers[i].getAttribute("lng")));
						  var html = "<b>" + name + "</b> <br/>" + address;
						  var icon = customIcons[type] || {};
						  bindInfoWindow(m, map, infoWin, html);
						  var listt = createSidebarEntry(m, name, address, image);
						  document.getElementById("content_list").appendChild(listt);
						
						/**************list in sidebar******************/
			}	
        }
      });

				//add clear overlay button on overlaycomplete,not sure if it is working
				var controlDiv = document.getElementById("control-div");
				var controlUI = document.getElementById("control-ui");
				var controlText = document.getElementById("control-text");
				controlUI.click(function() {
					map.setZoom(11);
				 });
				map.controls[google.maps.ControlPosition.TOP_RIGHT].push(controlDiv);
				
	});

  
   
   
	  
	  
	  
	  
	  /**********controls ****************************/
	  
	  
	  
      var infoWindow = new google.maps.InfoWindow;

      // Change this depending on the name of your PHP file
      downloadUrl("phpsqlajax_genxml.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 image = markers[i].getAttribute("image");
          var point = new google.maps.LatLng(
              parseFloat(markers[i].getAttribute("lat")),
              parseFloat(markers[i].getAttribute("lng")));
          var html = "<b>" + name + "</b> <br/>" + address;
          var icon = customIcons[type] || {};
          var marker = new google.maps.Marker({
            map: map,
            position: point,
            icon: icon.icon
          });
		  markersToRemove.push(marker);
          bindInfoWindow(marker, map, infoWindow, html);
		  var listt = createSidebarEntry(marker, name, address, image);
		  document.getElementById("content_list").appendChild(listt);
        }
      });
    }

    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() {}
//create sidebar entry for properties
function createSidebarEntry(marker, name, address, image) {
      var div = document.createElement('div');
	  var html ='<div class="images"><img src ="'+image+'" class="images_property" height="100px" width="100px"/></div>';
      html += '<div class="content"><b class="title">' + name + '</b><p class="address">' + address + '</p></div>';
      div.innerHTML = html;
	  div.className = "list_item";
      div.style.cursor = 'pointer';
	  div.style.float = 'left';
	  div.style.width = '100%';
      div.style.marginBottom = '5px'; 
	  google.maps.event.addDomListener(div, 'click', function() {
        google.maps.event.trigger(marker, 'click');
      });
     return div;
    }
</script>

 <body onload="load()">
  <div class="container">
    <div id="map" style="width: 60%; height: 800px;float:left;"></div>
	<div id="content_list" style="width: 40%; height: 800px;float:left;overflow: auto;"></div>
	</div>
</body>
.list_item {
     cursor: pointer;
    float: left;
    height: 110px;
    margin-bottom: 5px;
    width: 100%;
}
.images {
    float: left;
    height: 100px;
}

.content {
    float: left;
    height: 100px;
	padding:5px;
}
.title{
color :#0074e4;
font-size:15px;
}
.address{
color :#666;
}
.top{
	position: absolute;
    transition: width 0.3s ease 0s;
    z-index: 21;
}

Before drawing map looks like

google_maps_all_list

After drawing map looks like

google_maps

Advertisements