Koneksi Php, MySQL, dan Google Maps API

Posted by admin on 30 May, 2011
12 Comments
This item was filled under [ GIS ]

Kembali dengan tutorial google maps. Untuk kali ini, pembahasan akan mengarah pada bagaimana kita
menampilkan suatu peta ke dalam google maps dalam bentuk marker yang diload dari dalam database. Selain
itu, kita tidak perlu terlalu banyak melakukan “hard coding” tetapi cukup menggunakan class/library yang
sudah ada di aplikasi DrasticTools. Untuk mendownload sample dan gallery tentang google maps yang ada
pada DrasticTools, silakan Anda dapat kunjungi http://www.drasticdata.nl. Dan yang lebih keren lagi, aplikasi
ini dirilis dibawah GPL. Jadi ya silakan pembaca blog saya, dapat mengeksplor lebih jauh lagi digabungkan
dengan teknik-teknik menawan Jquery atau Ajax. Langsung saja, saat ini persiapan kita adalah :
1. Buat folder baru di folder utama web misal /htdocs/maps1/ atau /www/maps1/.
2. Siapkan data untuk MySQL dengan format bebas, asalkan ada kolom “Coords” untuk inisialisasi koordinat
Longitude dan Latitude. Sehingga, google bisa membaca record-record di kolom Coords dan ditampilkan
sesuai dengan koordinatnya di peta google maps. Untuk nama database yang saya pakai adalah “drasticdata”
dengan nama tabel “country_map”. Isi dari SQL-nya misalnya untuk daerah Bandung adalah sebagai berikut:
Struktur tabel:
1 DROP TABLE IF EXISTS `country_map`;
2 CREATE TABLE `country_map` (
3
`id` INT(11) NOT NULL AUTO_INCREMENT,
4
`Code` CHAR(3) COLLATE utf8_unicode_ci NOT NULL,
5
`nama_kec` CHAR(52) COLLATE utf8_unicode_ci NOT NULL,
6
`Luas_Area` FLOAT(10,2) NOT NULL DEFAULT '0.00',
7
`Jumlah_Penduduk` INT(11) NOT NULL DEFAULT '0',
8
`Kepadatan` INT(11) NOT NULL DEFAULT '0',
9
`Pelanggan_MA` CHAR(45) COLLATE utf8_unicode_ci NOT NULL,
10
`Coords` CHAR(30) COLLATE utf8_unicode_ci NOT NULL DEFAULT '-6.907, 107.609',
11
PRIMARY KEY (`id`)
12 ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=273
;

Pengisian Data:
1
2
3
4
5
6
7
8
9
10
11
12
13

INSERT INTO `drasticdata`.`country_map`
`Kepadatan`, `Pelanggan_MA`, `Coords`)
VALUES
('1',
'AAN',
'Astana Anyar',
('2',
'BTN'
,'Batu Nunggal',
('3',
'BKL',
'Bojong Loa Kaler',
('4',
'CBK',
'Cibeunying Kidul',
('5',
'ADR',
'Andir',
'3.93',
('6',
'SJD',
'Sukajadi', '5.26',
('7',
'RGL',
'Regol',
'4.5',
('8',
'BBK', 'Babakan Ciparay',
('9',
'BKL',
'Bandung Kulon',
('10',
'KCN',
'Kiara Condong',

(`id`, `Code`, `nama_kec`, `Luas_Area`,`Jumlah_Penduduk`,

'2.7',
'4.76',
'3.01',
'4.08',
'93708',
'95455',
'96159',
'7.16',
'6.48',
'5.59',

'73241', '27126',
'117753', '24738',
'106867', '35504',
'100927', '24737',
'23844'
,'1669'
'18147',
'1270',
'21369',
'1496',
'108725', '15185',
'120733', '18632',
'115305', '20627',

'1899',
'-6.8612,107.5963'),
'1732',
'-6.9274,107.6457'),
'2485',
'-6.9297, 107.5990'),
'1732',
'-6.9008, 107.6534'),
,'-6.9064, 107.5801'),
'-6.8918, 107.5971'),
'-6.9366, 107.6217'),
'1063',
'-6.9310, 107.5846'),
'1304',
'-6.9302, 107.5767'),
'1444',
'-6.9258, 107.6540'),

'5.0 Strict//EN" "http://www. 107. 'Buah Batu'. include ("class_library. } } $src = new mysrc($server.6942'). '107946'.93'.9200. $db. $pw="". ('14'.'60990'. '5. 107. 107. '804'. '5. '552'. '11. ('28'.6915'). '34890'. '-6. '5567'. 'Cicendo'.9084. 'Antapani'.js"></script> <script type="text/javascript" src="js/mootools-1. '-6. '380'. 107. '39535'. '5. 107.9041.11'. 'Rancasari'.29'. '4. '441'. '4. 'Bandung Kidul'. 'GDB'. '-6.623'). 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 <?php include ("config. '7. ('25'.35'.8616. '-6. 'LEN'. '45956'.9408. 'Cinambo'. $pw. 107. 'Cidadap'. ('23'. '12. 'Panyileukan'. ('21'. '5237'. '434'. ('24'. '34518'.33'. 'PAN'. '367'. '11493'. 107. '-6. ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.org/TR/xhtml1/DTD/xhtml1-strict.6767'). 'Sumur Bandung'. $this->conn) or die(mysql_error()). 'CMB'. class mysrc extends drasticsrcmysql { protected function select(){ $res = mysql_query("SELECT * FROM $this->table WHERE daerah='bandung'" .6267').6644'). '7023'. 'RAN'.55'. '7892'. 'Bandung Wetan'.css"/> <link rel="stylesheet" type="text/css" href="css/map_default.56'. 1 2 3 4 5 6 7 8 9 <?php $server="localhost". '8287'. 107. ('26'. 3. 107. '3. '-6. ('17'.php untuk menampilkan peta utama. ('27'. '19964'. 107. '14687'. '-6. 107. 107. '6305'. ('13'. '6. '11968'. ('18'.js"></script> . 'Cibeunying Kaler'. '63742'. '15. '93456'. $GApiKey="silakan Anda generate untuk Google API Key-nya".36'.9135.14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 ('11'. '-6.6281').35'.57'. '59193'.6456'). '-6. '3.920. '10. '52137'. '5432'. Buatlah file bernama tampil_peta. return ($res). '815'. 'Ujung Berung'. '-6. '580'. '838'. '1045'. '38694'. '-6.03'.4'. 'SKS'. 'Cibiru'.6661'). '492'. '165'. '-6. '-6. 'Lengkong'.13'. 'BHB'. '57365'. 'CBY'. '16674'.6046').955'). '27328'. 'BKD'. ('15'.5963'). Buatlah file bernama config.9525. '6196'. '390'.44'. 'CCD'. "country_map"). $db="drasticdata".2-more. 107.js"></script> <script type="text/javascript" src="js/drasticGrid. $user.05'.css"/> <title>Mobile Advertising Market Spread</title> </head> <html> <body> <script type="text/javascript" src="js/mootools-1.6915'). '70969'. '-6.php untuk koneksi ke databasenya. ('16'. '82633'.7165').6086'). '114'. 'MAN'. 107. '10477'. 107. 'Gede Bage'. '67529'. '11638'.23'.2-core. 'CID'. 'Coblong'. 'BWT'. '70492'. $user="root". 'ATP'.dtd"> <html xmlns="http://www. '733'.653.2'. '-6.w3. 107.8900. '82722'. '1028'.8848. ('22'. 107.php"). 'SMB'. '6289'. 'Bojong Loa Kidul'.51'. ('20'. '7. '7. ?> 4.8612. 'CBL'. 'Mandala Jati'.9447. '10. '962'. '2362'. ('30'. '1167'. 107.9222. '8280'. 'BKD'. $table="country_map".6275'). 107.78'.php"). 'CIB'. 'Suka Sari'. '-6. '8. ('29'. 107. '580'. '-6. '14934'. '-6. ('19'. $this->orderbystr. '8.9343. '-6. '65711'. 'Arcamanik'.9318. 'UJB'. 'ARC'.9052. '-6. '440'.9120.6234'). '13741'.org/1999/xhtml" lang="en" xml:lang="en"> <head> <link rel="stylesheet" type="text/css" href="css/grid_default. ('12'.7002'). '13. '1632'.9165.w3.6384').6266').9408.5'.

var thegrid = new drasticGrid('grid1'. onClick: function(id){themap. $wherestr. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 <?php class drasticSrcMySQL { // these options should be set via the options argument on the constructor! public $add_allowed = true. $pw. public $num_fields.28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 <script type="text/javascript" src="http://maps. { pathimg: "img/". onClick: function(id){themap.DefaultOnClick(id)."></div> <div id="grid1"></div> <script type="text/javascript"> var themap = new drasticMap('map1'. public $cols_numeric. $table. public $sort. $user.js"></script> <div id="map1" style="width: 740px. public $idname. public $SQLCharset public $HTMLCharset // name of column to sort on // sort ascending (a) = "utf8". public $num_rows.DefaultOnClick(id). public $result. only records that satisfy these conditions will be selected. or descending (d)? Default is a.DefaultOnClick(id)} }). Defaults to the id column. height: 300px. { pathimg: "img/". public $idcolnr. // character set for xhttprequest // General variables public $orderbystr. Jangan lupa buatlah file class_library. displaycol: "nama_kec". // added records public $sortcol. // array of columnnames to be editable.com/maps?file=api&v=2&key=<?php echo $GApiKey ?>"></script> <script type="text/javascript" src="js/markermanager.js"></script> <script type="text/javascript" src="js/drasticMap. private $max. thegrid. </script> </body></html> 5. if (isset($options["delete_allowed"])) $this->delete_allowed = . Defaults to all columns except the id column public $defaultcols. // character set of the strings in the table = "UTF-8".php untuk menyimpan file-file class yang ada di DrasticTools. public $editablecols.DefaultOnClick(id)} }). if ($options) { if (isset($options["add_allowed"])) $this->add_allowed = $options["add_allowed"].google. $options = null) { if (!isset($_REQUEST["op"])) return. $addstr. $db. // may the user add records? Default is true. // may the user delete records? Default is true. function __construct($server. thegrid. public $cols. pagelength: 10. initially. public $delete_allowed = true. // array of columnnames and values.

(isset($options["SQLCharset"])) $this->SQLCharset= $options["SQLCharset"]. (isset($options["sort"])) $this->sort= $options["sort"]. $flddefault. $fldtype. $this->idcolnr = $i. "'". $this->conn) or die(mysql_error()). } } $this->cols[] = $fld->name. for($i=0. $this->idcolnr = $i. $i++) { $fld = mysql_fetch_field($idresult. . if ($fld->numeric == 1) $this->cols_numeric[] = $fld->name. $i++) { list($fldname. // Initialize the name of the id field. column names and numeric columns: $idresult = $this->metadata(). $fldkey. $this->table. if ($primary_found == false) { if ($fld->primary_key == 1) { $this->idname = $fld->name. } /* Optionally retrieve parameters from the addparams parameter. * Uncomment the line below and change "myparameter" to the name of your parameter * If you pass multiple parameters copy the line multiple times * * $myparameter = $_REQUEST["myparameter"]. $this->conn). mysql_select_db($db) or die (mysql_error()). $primary_found = false. for($i=0. $fldnull.37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 $options["delete_allowed"]. if ($fldname != $this->idname) $this->editablecols[] = $fldname. $res = mysql_query("SET NAMES '" . for($i=0. 0). $i < mysql_num_rows($colresult). */ $this->conn = mysql_connect($server. $primary_found = true. } elseif ($fld->unique_key == 1) { $this->idname = $fld->name. } mysql_free_result($colresult). $i < mysql_num_fields($idresult). $i < mysql_num_fields($idresult). (isset($options["sortcol"])) $this->sortcol= $options["sortcol"]. $fldextra) = mysql_fetch_row($colresult). $user. $this->table = $table. $i). $colresult = mysql_query("SHOW COLUMNS FROM " . } if (!isset($this->idname)) die("Could not find primary or unique key"). // Initialize Field types: $this->fldtypes = array(). if (isset($options["HTMLCharset"])) $this->HTMLCharset= $options["HTMLCharset"]. if (isset($options["editablecols"])) $this->editablecols = $options["editablecols"]. $this->fldtypes[$fldname] = $fldtype. // Initialize editablecols if not done yet: if (!isset($this->editablecols)) { mysql_field_seek($idresult. $i++) { $fldname = mysql_fetch_field($idresult)->name. } } mysql_free_result($idresult). if if if if (isset($options["defaultcols"])) $this->defaultcols= $options["defaultcols"]. $pw) or die(mysql_error()). $this->SQLCharset .

switch ($op) { case ("a") : if ($this->add_allowed) exit($this->add()).$this- >HTMLCharset). must-revalidate" ). " = '" . array_values($this->defaultcols))). if (isset($_REQUEST["sort"])) $this->sort = mysql_real_escape_string($_REQUEST["sort"]). $value .99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 // Calculate the WHERE string and the string for the ADD operation. $wherestr1 = implode(" AND ". header( "Expires: Mon. $assignment). $this->sortcol . $addstr2 = implode(". if ($this->defaultcols){ foreach ($this->defaultcols as $key => $value) $assignment[] = $key . array_keys($this->defaultcols)). if if if if if if ($op ($op ($op ($op ($op ($op == == == == == == "v") exit($this->view()). "vrn") exit($this->view_rownr()). header( "Pragma: no-cache" ). if (!$this->sortcol) $this->sortcol = $this->idname. } function __destruct() { if ($this->result) mysql_free_result($this->result). $addstr1 = implode(". } private function view_meta(){ $result[0] = $this->num_rows. d M Y H:i:s" ) . "vc") exit($this->view_circle()). } // Do the sorting: if (isset($_REQUEST["sortcol"])) $this->sortcol = mysql_real_escape_string($_REQUEST["sortcol"]). ($op != "vb" && $op != "vc") header("Content-Type: text/html. $this->wherestr = sprintf(" WHERE %s ". gmdate( "D. "vm") exit($this->view_meta()). header( "Cache-Control: no-cache. ". $this->num_rows = mysql_num_rows($this->result). "addquotes"). 26 Jul 1997 05:00:00 GMT" ). $this->addstr = " () VALUES () ". "'". "vb") exit($this->view_bar()). case ("d") : if ($this->delete_allowed) exit($this->delete($id)). . $this->wherestr = "". $this->num_fields = mysql_num_fields($this->result). if ($this->conn) mysql_close($this->conn). rawurldecode($value))). if (isset($_REQUEST["op"])) $op = $_REQUEST["op"]. else $op = "". (isset($_REQUEST["col"])) $col = $_REQUEST["col"]. $col. $this->addstr = sprintf(" (%s) VALUES (%s) ". charset=". (isset($_REQUEST["value"])) $value = $_REQUEST["value"]. " GMT" ). "vl") exit($this->view_label()). case ("u") : exit($this->update($id. if the defaultcols option is set. if (!$this->sort) $this->sort = "a". $this->orderbystr = " ORDER BY " . if if if if (isset($_REQUEST["id"])) $id = $_REQUEST["id"]. // disable IE caching header( "Last-Modified: " . ". } // Get the table in memory $this->result = $this->select(). $addstr2). array_map(array ($this. $wherestr1). ($this->sort == "d"?" DESC":""). $addstr1.

172 $result[12] = $this->fldtypes. 222 . else return(false). 188 } 189 // Override this function if you want to use (join) query on multiple tables: 190 protected function metadata(){ 191 $res = mysql_query("SELECT * FROM $this->table LIMIT 1". $i < mysql_num_rows($res). $this181 >orderbystr. $fld = "") { 199 $res = $this -> select(). 220 mysql_query("DELETE FROM $this->table WHERE $this->idname='$id'". 183 } 184 protected function add(){ 185 mysql_query("INSERT INTO $this->table" . 170 $result[10] = $this->sortcol. $i++) { 213 $row = mysql_fetch_array($res). 168 $result[8] = $this->editablecols. 162 $result[2] = $this->idname. 193 } 194 195 // 196 // Private functions only visible within the class 197 // 198 private function exists($id. 173 return(json_encode($result)). $this->wherestr . 165 $result[5] = $this->cols_numeric. 200 // check field 201 if ($fld != "") { 202 $found = false. 171 $result[11] = $this->sort.161 $result[1] = $this->num_fields. 169 $result[9] = $this->defaultcols. 214 if ($row[$this->idcolnr] == $id) return(true). 164 $result[4] = $this->cols. 203 while (($field = mysql_fetch_field($res)) != null) { 204 if ($field->name == $fld) { 205 $found = true. 206 break. 217 } 218 private function delete($id){ 219 if (!$this->exists($id)) return(false). 210 } 211 // check id 212 for ($i=0. 192 return ($res). 182 return ($res). $this221 >conn) or die(mysql_error()). $this->addstr. $this->conn) or 186 die(mysql_error()). 174 } 175 // 176 // These protected functions can be overruled if you want to redefine your datasource 177 // 178 179 protected function select(){ 180 $res = mysql_query("SELECT * FROM $this->table" . 207 } 208 } 209 if (!$found) return(false). $this->conn). $this->conn) or die(mysql_error()). 166 $result[6] = $this->add_allowed. 187 if (mysql_affected_rows($this->conn) == 1) return(true). 215 } 216 return(false). 167 $result[7] = $this->delete_allowed. 163 $result[3] = $this->idcolnr.

$value){ if ((in_array($fld.223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 if (mysql_affected_rows($this->conn) == 1) return(json_encode(true)). $this>num_fields). } else { $res = mysql_query("SELECT $fld FROM $this>table WHERE $this->idname='$id'".$_REQUEST["id"]. if ($end > $this->num_rows) $end = $this->num_rows. $fld. } private function view_rownr(){ if (isset($_REQUEST["id"])){ mysql_data_seek($this->result. $this->conn) or die(mysql_error()). } $arr[0] = $row. else return("0"). else return(json_encode(false)). if (mysql_affected_rows($this->conn) == 1) { return("1"). for ($j = 0. $this->editablecols)) && $this->exists($id. $this->conn) or die(mysql_error()). $sqlidarr[0] = $value[$this->idname]. if ($value[$this->idcolnr] == $_REQUEST["id"]) { return(json_encode($i)). $j < ((isset($cols))?(count($cols)):($this->num_fields))." = '". $i++) { $value = mysql_fetch_array($this->result). $i++) { $value = mysql_fetch_array($this->result). } } } return(json_encode(-1)). if ($start < $this->num_rows) { mysql_data_seek($this->result. $start). } else { if (isset($_REQUEST["start"])) $start = $_REQUEST["start"]. $this->conn). $i < ($end-$start). if ($row[0] == $value) return("1"). else $start = 0. for ($i = 0. mysql_free_result($res). for ($j = 0.$this>idname. 0). } private function view(){ if ($this->num_rows == 0) return(json_encode(array(null. if (isset($_REQUEST["id"])){ $res = mysql_query("SELECT * FROM $this->table WHERE ". if ($start < 0) $start=0. if (isset($_REQUEST["cols"])) $cols = explode(". if (isset($_REQUEST["end"])) $end = $_REQUEST["end"]. $row = mysql_fetch_array($res). $_REQUEST["cols"]. $j++) { $row[$j] = $value[((isset($cols))?($cols[$j]):($j))]."'". $j < . $fld)) { mysql_query("UPDATE $this->table SET $fld='$value' WHERE $this>idname='$id'". $i < $this->num_rows. } private function update($id. } } return("0").". null))). for ($i = 0. else $end= $this->num_rows. $value = mysql_fetch_array($res).

$r = sqrt($opp / pi()). //echo $row[$j]. } private function view_bar(){ $id = $_REQUEST["id"]. TRUE). $result[1] = $arr. $colname = $_REQUEST["colname"]. $h = $_REQUEST["h"]. $h. $data = mysql_fetch_array($res). if (!isset($this->max)) $this->max = $this->MaxNumber($colname). $bg = imagecolorallocatealpha($im. 0. imagesavealpha($im. mysql_free_result($res). 0. $this->conn) or die(mysql_error()). . 127). $maxr = $w / 2. $w = $_REQUEST["w"]. $res = mysql_query("SELECT $colname FROM $this->table WHERE $this>idname='$id'". imagealphablending($im. $value = $data[0]. Header("Content-type: image/png"). imagefilledrectangle ($im. return(json_encode($result)). } private function view_circle(){ $id = $_REQUEST["id"]. mysql_free_result($res). $h-$height. $sqlidarr[$i] = $value[$this->idname]. $im = imagecreatetruecolor ($w. 2). 255. $h) or die("Cannot Initialize new GD image stream"). 255. $value = $data[0]. 255. imagefill($im. ImageDestroy($im). $this->conn) or die(mysql_error()). $w. $maxopp = pi() * pow($maxr. if (!isset($this->max)) $this->max = $this->MaxNumber($colname). $clr = imagecolorallocatealpha($im. $bg). } } } $result[0] = $sqlidarr. $colname = $_REQUEST["colname"]. $w = $_REQUEST["w"]. $j++) { $row[$j] = $value[((isset($cols))?($cols[$j]):($j))]. $clr). 0.285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 ((isset($cols))?(count($cols)):($this->num_fields)). $width = $r*2. 60). $opp = $maxopp * ($value / $this->max). 0. 255. } $arr[$i] = $row. Imagepng($im). FALSE). $im = imagecreatetruecolor ($w. $data = mysql_fetch_array($res). $res = mysql_query("SELECT $colname FROM $this->table WHERE $this>idname='$id'". $w) or die("Cannot Initialize new GD image stream"). $height = (int) ceil($h * ($value / $this->max)). 0.

0). } function addquotes($str) { return ("'". 0. } private function MaxNumber($colname) { $max = 0. for ($i=0. 0. 255. 255. 60). langsung saja habis itu. $maxr. imagesavealpha($im. 255. $width. . FALSE). 127). $bg = imagecolorallocatealpha($im. Header("Content-type: image/png"). Imagepng($im). 255. kita buka browser kesayangan kita misal di google chrome dengan alamat http://localhost/maps1. 0. $i++) { $row = mysql_fetch_array($this->result). 0. $width. $i < $this->num_rows. $max = max($max. ImageDestroy($im). } } ?> Nah. Selamat Mencoba! Untuk tampilannya menyusul ya. } return($max). mysql_data_seek($this->result. 360."'"). 0. $maxr. imagefilledarc ($im. $bg). imagefill($im. $clr = imagecolorallocatealpha($im. $row[$colname]).$str.imagealphablending($im. $clr. TRUE). IMG_ARC_PIE).

Sign up to vote on this title
UsefulNot useful