Google Map With Database(with multiple marker)

===========================================================

Create  TABLE >>marker to database

===========================================================

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,

  `type` varchar(30) NOT NULL,

  PRIMARY KEY (`id`)

) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=10 ;

--

-- Dumping data for table `markers`

--

INSERT INTO `markers` (`id`, `name`, `address`, `lat`, `lng`, `type`) VALUES

(1, 'Pan Africa Market', '1521 1st Ave, Seattle, WA', 47.608940, -122.340141, 'restaurant'),

(2, 'Buddha Thai & Bar', '2222 2nd Ave, Seattle, WA', 47.613590, -122.344391, 'bar'),

(3, 'The Melting Pot', '14 Mercer St, Seattle, WA', 47.624561, -122.356445, 'restaurant'),

(4, 'Ipanema Grill', '1225 1st Ave, Seattle, WA', 47.606365, -122.337654, 'restaurant'),

(5, 'Sake House', '2230 1st Ave, Seattle, WA', 47.612823, -122.345673, 'bar'),

(6, 'Crab Pot', '1301 Alaskan Way, Seattle, WA', 47.605961, -122.340363, 'restaurant'),

(7, 'Mama''s Mexican Kitchen', '2234 2nd Ave, Seattle, WA', 47.613976, -122.345467, 'bar'),

(8, 'Wingdome', '1416 E Olive Way, Seattle, WA', 47.617214, -122.326584, 'bar'),

(9, 'Piroshky Piroshky', '1908 Pike pl, Seattle, WA', 47.610126, -122.342834, 'restaurant');






===========================================================

THIS IS FIRST EXAMPLE

http://tips4php.net/2010/10/use-php-mysql-and-google-map-api-v3-for-displaying-data-on-map/

===========================================================



 <style>
.map_div{width:334px; float:left; padding:0px; margin:0px; font-family:Arial, Helvetica, sans-serif;margin-left:-2px}

body:nth-of-type(1) .map_div{width:334px; float:left; padding:0px; margin:0px; font-family:Arial, Helvetica, sans-serif;margin-left:0px}
.map_div_top{ width:334px; float:left; padding:0px 0px 0px 0px; margin:0px; background:url(map/map_top.png) top center no-repeat; font-size:14px; color:#FFF; text-transform:uppercase; margin-top:-11px;*margin-top:-10px;}
.map_div_top_heading{ width:298px; float:left; padding:17px 0px 0px 15px;  margin:0px; font-size:14px; color:#FFF; text-transform:uppercase;}
.map_div_top_icon{ width:12px; float:left; padding:20px 0px 0px 0px; margin:0px;}
.map_div_2{ width:332px; float:left; padding:0px; margin:0px; border:1px #40403f solid; }
.map_tex_div{ width:305px; float:left; padding:10px 0px 10px 0px; margin:0px 0px 0px 15px; border-bottom:1px #333 solid;}
.map_tex_div h1{ font-size:15px; float:left; padding:2px 0px 2px 0px; margin:0px; color:#333;}
.map_tex_div h1 a{color:#333333;text-decoration:none}
.map_tex_div h1 a:hover {color:#333333;text-decoration:underline }

.map_tex_div h2{ font-size:13px; float:left; padding:5px 0px 0px 0px; margin:0px; color:#666; line-height:18px;}
.map_tex_div h2 a{ color:#333; text-decoration:none;}
.map_tex_div h2 a:hover{ color:#333; text-decoration:underline; }
.map_div_3{ width:305px; float:left; padding:5px 0px 7px 0px; margin:0px 0px 0px 15px; }
.map_email_div{ width:135px; float:left; padding:0px 0px 0px 24px;*padding:0px 0px 0px 24px; margin:6px 0px 0px 0px; background:url(map/map_email_icon.jpg) left no-repeat; height:13px;font-size:12px; color:#333; text-transform:uppercase; }
.map_email_div a{ color:#333; text-decoration:none; border:0px; }
.map_email_div a:hover{ color:#333; text-decoration:underline; }
.map_get_directions{ width:142px; float:left; padding:0px; margin:0px; border:0px !important; }

</style>
    <script type="text/javascript">
    //<![CDATA[
var customIcons = {
  0: {
    icon: 'gif_blue.gif',
    shadow: 'gif_blue.gif'
  },
  1: {
    icon: 'gif_green.gif',
    shadow: 'gif_green.gif'
  }
};

function load() {
  var map = new google.maps.Map(document.getElementById("map_canvas"), {
 
   <?php if($_REQUEST['lat']!="" && $_REQUEST['lng']!="") {?>
      center: new google.maps.LatLng('<?= $_REQUEST['lat'] ?>','<?= $_REQUEST['lng'] ?>'),
      zoom: 7,
      mapTypeId: google.maps.MapTypeId.ROADMAP

    <?php }else { ?> 
      center: new google.maps.LatLng(-37.822075,145.287964),
      zoom: 4,
      mapTypeId: google.maps.MapTypeId.ROADMAP
   <?php } ?>
  });

  // Change this depending on the name of your PHP file
 // Change this depending on the name of your PHP file
downloadUrl("blog_xml.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
var newMarkers = [];
for (var i = 0; i < markers.length; i++) {
//alert(markers.length);
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("email");
var site = markers[i].getAttribute("website");
var d_id = markers[i].getAttribute("d_id");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));

// var html = "<b>" + name + "</b> <br/>" + address;
var href="<a href=mailto:"+type+">";
var wsite='<a href='+site+' target=blank>';
var id="<a href=dealer_detail.php?id="+d_id+">";
//alert(address);
//var ggl=address;
var googlelink ="http://maps.google.com/?daddr="+address+"";
var ggl="<a href='"+googlelink+"' target=blank><img src='map/get_directions.jpg' width=142 height=27 alt='' /></a>";
//alert(ggl);
var boxText = document.createElement("div");
boxText.style.cssText = "background:white";
//boxText.innerHTML = "Nom : <b>" + name + "</b><br><b>" + site + "</b><br/>Adresse :" + address + "</b><br/>"+href+""+type+"</a>";

boxText.innerHTML ='<div class="map_div" style="margin-top:-10px;*margin-top:5px;background:#fff;margin-left:-1px"><div class="map_div_top" style="height:40px"><div class="map_div_top_heading">'+name+'</div></div><div class="map_div_2"><div class="map_tex_div"><h1>'+id+''+name+'</a></h1><h2>'+address+'<br>'+wsite+''+site+'</a></h2></div><div class="map_div_3"><div class="map_email_div">'+href+'Email Dealer</a></div><div class="map_get_directions">'+ggl+'</div></div></div></div>';

//alert(boxText.innerHTML);

var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon:"http://www.kokodacaravans.com.au/images/new-icon.png",
shadow: icon.shadow
});

newMarkers.push(marker);

var myOptions = {

content: boxText

,disableAutoPan: false
,maxWidth: 0
,pixelOffset: new google.maps.Size(-140, 0)
,zIndex: null
,boxStyle: {
background: "url('tipbox.gif') no-repeat"
,opacity:""
,width: "334px"
}
,closeBoxMargin: "12px 4px -7px 2px"
,closeBoxURL: "http://www.google.com/intl/en_us/mapfiles/close.gif"
,infoBoxClearance: new google.maps.Size(1, 1)
,isHidden: false
,pane: "floatPane"
,enableEventPropagation: false
};

newMarkers[i].infobox = new InfoBox(myOptions);
//THE PROBLEM SHOULD BE HERE :
google.maps.event.addListener(marker, 'mouseover', (function(marker, i) {
return function() {
for ( h = 0; h < newMarkers.length; h++ ) {
newMarkers[h].infobox.close();
}
newMarkers[i].infobox.open(map, marker);
}
})(marker, i));

}

});

}

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() {}

        for (var i = 0; i < numMarkers; i++) {
            createMarker(markers[i]);
        }

  </script>















===========================================================

THIS IS SECOND EXAMPLE



BELOW EXAMPLE FOR CUSTOMIZE THE INFOBOX WITH MYSQL

5 FILE USED FOR THIS
  1.  index.php
  2. phpsqlajax_dbinfo.php
  3. XML.PHP
  4. JS>>http://maps.googleapis.com/maps/api/js?v=3&amp;sensor=false
  5. http://code.google.com/p/google-maps-utility-library-v3/source/browse/trunk/infobox/src/infobox.js?r=49
CODE 

===========================================================
FILE>>phpsqlajax_dbinfo.PHP
===========================================================


 <?php

$username="USERNAME";

$password="PASSWORD";

$database="DATABASENAME";

?>

===========================================================

FILE>>Index.php
===========================================================



<html>
<head>

<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?v=3&amp;sensor=false"></script>

<script type="text/javascript" src="../src/infobox.js"></script>

    <script type="text/javascript">

    //<![CDATA[

var customIcons = {

  0: {

    icon: 'gif_blue.gif',

    shadow: 'gif_blue.gif'

  },

  1: {

    icon: 'gif_green.gif',

    shadow: 'gif_green.gif'

  }

};

function load() {

  var map = new google.maps.Map(document.getElementById("map_canvas"), {

        center: new google.maps.LatLng(47.608940, -122.340141),

    zoom: 14,

    mapTypeId: 'terrain'

  });

  // Change this depending on the name of your PHP file

 // Change this depending on the name of your PHP file

downloadUrl("xml.php", function(data) {

var xml = data.responseXML;

var markers = xml.documentElement.getElementsByTagName("marker");

var newMarkers = [];

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;

var boxText = document.createElement("div");

boxText.style.cssText = "border: 1px solid black; margin-top: 8px; background: yellow; padding: 5px;";

boxText.innerHTML = "Nom : <b>" + name + "</b> <br/>Adresse :" + address + "</b> <br/>Type :" + type;

var icon = customIcons[type] || {};

var marker = new google.maps.Marker({

map: map,

position: point,

icon: icon.icon,

shadow: icon.shadow

});

newMarkers.push(marker);

var myOptions = {

content: boxText

,disableAutoPan: false

,maxWidth: 0

,pixelOffset: new google.maps.Size(-140, 0)

,zIndex: null

,boxStyle: {

background: "url('tipbox.gif') no-repeat"

,opacity: 0.75

,width: "280px"

}

,closeBoxMargin: "10px 2px 2px 2px"

,closeBoxURL: "http://www.google.com/intl/en_us/mapfiles/close.gif"

,infoBoxClearance: new google.maps.Size(1, 1)

,isHidden: false

,pane: "floatPane"

,enableEventPropagation: false

};

newMarkers[i].infobox = new InfoBox(myOptions);

//THE PROBLEM SHOULD BE HERE :

google.maps.event.addListener(marker, 'mouseover', (function(marker, i) {

return function() {

for ( h = 0; h < newMarkers.length; h++ ) {

newMarkers[h].infobox.close();

}

newMarkers[i].infobox.open(map, marker);

}

})(marker, i));

}

});

}

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() {}

        for (var i = 0; i < numMarkers; i++) {

            createMarker(markers[i]);

        }

  </script>

  </head>

  <body onLoad="load()">

    <div id="map_canvas" style="width: 1000px; height: 300px"></div>

  </body>

</html>
===========================================================

===========================================================

FILE>>xml.PHP

===========================================================
<?php
require("phpsqlajax_dbinfo.php");

function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','&lt;',$htmlStr);
$xmlStr=str_replace('>','&gt;',$xmlStr);
$xmlStr=str_replace('"','&quot;',$xmlStr);
$xmlStr=str_replace("'",'&apos;',$xmlStr);
$xmlStr=str_replace("&",'&amp;',$xmlStr);
//$xmlStr=str_replace("-",'&ndash;',$xmlStr);

    
return $xmlStr;
}

// 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 dealer_master where currentstatus=0 ";
$result = mysql_query($query);
if (!$result) {
  die('Invalid query: ' . mysql_error());
}

header("Content-type: text/xml");

// Start XML file, echo parent node
echo '<markers>';

// Iterate through the rows, printing XML nodes for each
while ($row = @mysql_fetch_assoc($result)){
  // ADD TO XML DOCUMENT NODE
  echo '<marker ';
  echo 'name="' . parseToXML($row['name']) . '" ';
  echo 'email="' . $row['email'] . '" ';
  echo 'website="' . $row['website'] . '" ';
  echo 'd_id="' . $row['d_id'] . '" ';
  echo 'address="' . parseToXML($row['address']) . '" ';
  echo 'lat="' . $row['lat'] . '" ';
  echo 'lng="' . $row['lng'] . '" ';
  echo '/>';
}

// End XML file
echo '</markers>';

?>

===========================================================
 THIS IS THIRD EXAMPLE 
===========================================================
<html>
    <head>
    <script type='text/javascript' src='jquery-1.6.2.min.js'></script>
    <script type='text/javascript' src='jquery-ui-1.8.14.custom.min.js'></script>
    <style>

        BODY {font-family : Verdana,Arial,Helvetica,sans-serif; color: #000000; font-size : 13px ; }

        #map_canvas { width:100%; height: 100%; z-index: 0; }
    </style>
    <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false" /></script>
    <script type='text/javascript'>

    //This javascript will load when the page loads.
    jQuery(document).ready( function($){

            //Initialize the Google Maps
            var geocoder;
            var map;
            var markersArray = [];
            var infos = [];

            geocoder = new google.maps.Geocoder();
            var myOptions = {
                  zoom: 9,
                  mapTypeId: google.maps.MapTypeId.ROADMAP
                }
            //Load the Map into the map_canvas div
            var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
            map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

            //Initialize a variable that the auto-size the map to whatever you are plotting
            var bounds = new google.maps.LatLngBounds();
            //Initialize the encoded string      
            var encodedString;
            //Initialize the array that will hold the contents of the split string
            var stringArray = [];
            //Get the value of the encoded string from the hidden input
            encodedString = document.getElementById("encodedString").value;
            //Split the encoded string into an array the separates each location
            stringArray = encodedString.split("****");

            var x;
            for (x = 0; x < stringArray.length; x = x + 1)
            {
                var addressDetails = [];
                var marker;
                //Separate each field
                addressDetails = stringArray[x].split("&&&");
                //Load the lat, long data
                var lat = new google.maps.LatLng(addressDetails[1], addressDetails[2]);
                //Create a new marker and info window
                marker = new google.maps.Marker({
                    map: map,
                    position: lat,
                    //Content is what will show up in the info window
                    content: addressDetails[0]
                });
                //Pushing the markers into an array so that it's easier to manage them
                markersArray.push(marker);
                google.maps.event.addListener( marker, 'click', function () {
                    closeInfos();
                    var info = new google.maps.InfoWindow({content: this.content});
                    //On click the map will load the info window
                    info.open(map,this);
                    infos[0]=info;
                });
               //Extends the boundaries of the map to include this new location
               bounds.extend(lat);
            }
            //Takes all the lat, longs in the bounds variable and autosizes the map
            map.fitBounds(bounds);

            //Manages the info windows
            function closeInfos(){
           if(infos.length > 0){
              infos[0].set("marker",null);
              infos[0].close();
              infos.length = 0;
           }
            }

    });
    </script>

    </head>
    <body>
    <div id='input'>

        <?php

        //Connect to the MySQL database that is holding your data, replace the x's with your data
        mysql_connect("localhost", "xxxxx_xxx", "xxxx") or
         die("Could not connect: " . mysql_error());
        mysql_select_db("xxxxx_xxxx");

        //Initialize your first couple variables
        $encodedString = ""; //This is the string that will hold all your location data
        $x = 0; //This is a trigger to keep the string tidy

        //Now we do a simple query to the database
        $result = mysql_query("SELECT * FROM `big-ten`");

        //Multiple rows are returned
        while ($row = mysql_fetch_array($result, MYSQL_NUM))
        {
            //This is to keep an empty first or last line from forming, when the string is split
            if ( $x == 0 )
            {
                 $separator = "";
            }
            else
            {
                 //Each row in the database is separated in the string by four *'s
                 $separator = "****";
            }
            //Saving to the String, each variable is separated by three &'s
            $encodedString = $encodedString.$separator.
            "<p class='content'><b>Lat:</b> ".$row[1].
            "<br><b>Long:</b> ".$row[2].
            "<br><b>Name: </b>".$row[3].
            "<br><b>Address: </b>".$row[4].
            "<br><b>Division: </b>".$row[5].
            "</p>&&&".$row[1]."&&&".$row[2];
            $x = $x + 1;
        }       
        ?>

        <input type="hidden" id="encodedString" name="encodedString" value="<?php echo $encodedString; ?>" />
    </div>
    <div id="map_canvas"></div>
    </body>
</html>

1 comment: