Google Map API memberikan kemudahan bagi para pengembang untuk mengembangkan sebuah aplikasi berbasis lokasi / peta. Menarik dan cukup mudah untuk diikuti yang dirasakan oelh penulis saat membuat aplikasi web berbasis lokasi. 



Lalu apa saja yang bisa kita lakukan dengan Google Map API ini? jawabnanya banyak sekali. Teman-teman bisa temukan apa yang google map API buka untuk para developer di https://developers.google.com/maps/. Dan pada tutorial kali ini kita tidak akan membahas satu persatu, kita hanya memfokuskan untuk pembuatan marker. Dimana data yang kita masukan pada marker akan masuk ke dalam database.


Apa saja yang perlu di perhatikan disini?. Pada tutorial ini kita akan lebih memfokuskan diri untuk memahami dan mempelajari sintak javascript dan PHP pada pembuatan google maps marker.


Membuat Marker

Disini kita gunakan function create_marker untuk menampilkan sebuah marker pada tampilan google maps. Dimana marker akan tampil jika kita mengklik kanan pada peta.


//Create Marker Function
function create_marker(MapPos, MapTitle, MapDesc, InfoOpenDefault, DragAble, Removable, iconPath)
{

    //new marker
    var marker = new google.maps.Marker({
        position: MapPos,
        map: map,
        draggable: DragAble,
        animation: google.maps.Animation.DROP,
        title: "Hello World!",
        icon: iconPath
    });

    //Content structure of info Window for the Markers
    var contentString = $('<div class="marker-info-win">' +
            '<div class="marker-inner-win"><span class="info-content">' +
            '<h1 class="marker-heading">' + MapTitle + '</h1>' +
            MapDesc +
            '</span><button name="remove-marker" class="remove-marker" title="Hapus Marker">Hapus Marker</button>' +
            '</div></div>');


    //Create an infoWindow
    var infowindow = new google.maps.InfoWindow();
    //set the content of infoWindow
    infowindow.setContent(contentString[0]);

    //Find remove button in infoWindow
    var removeBtn = contentString.find('button.remove-marker')[0];
    var saveBtn = contentString.find('button.save-marker')[0];

    //add click listner to remove marker button
    google.maps.event.addDomListener(removeBtn, "click", function(event) {
        remove_marker(marker);
    });

    if (typeof saveBtn !== 'undefined') //continue only when save button is present
    {
        //add click listner to save marker button
        google.maps.event.addDomListener(saveBtn, "click", function(event) {
            var mReplace = contentString.find('span.info-content'); //html to be replaced after success
            var mName = contentString.find('input.save-name')[0].value; //name input field value
            var mDesc = contentString.find('textarea.save-desc')[0].value; //description input field value
            var mType = contentString.find('select.save-type')[0].value; //type of marker

            if (mName == '' || mDesc == '')
            {
                alert("Please enter Name and Description!");
            } else {
                save_marker(marker, mName, mDesc, mType, mReplace); //call save marker function
            }
        });
    }

    //add click listner to save marker button		 
    google.maps.event.addListener(marker, 'click', function() {
        infowindow.open(map, marker); // click on marker opens info window 
    });

    if (InfoOpenDefault) //whether info window should be open by default
    {
        infowindow.open(map, marker);
    }
}



Menghapus Marker

Function yang kita gunakan untuk menghapus marker pada peta google adalah remove_marker. Dimana marker akan di hapus ketika kita mengklik sebuah tautan atau link dengan tulisan "hapus marker"


//Remove Marker Function
function remove_marker(Marker)
{

    /* determine whether marker is draggable 
     new markers are draggable and saved markers are fixed */
    if (Marker.getDraggable())
    {
        Marker.setMap(null); //just remove new marker
    }
    else
    {
        //Remove saved marker from DB and map using jQuery Ajax
        var mLatLang = Marker.getPosition().toUrlValue(); //get marker position
        var myData = {del: 'true', latlang: mLatLang}; //post variables
        $.ajax({
            type: "POST",
            url: "map_process.php",
            data: myData,
            success: function(data) {
                Marker.setMap(null);
                alert(data);
            },
            error: function(xhr, ajaxOptions, thrownError) {
                alert(thrownError); //throw any errors
            }
        });
    }

}


Menyimpan Marker

Function save_marker kita gunakan untuk menyimpan data marker di database dengan prosess ajax. Yang nantinya permintaan akan di prosess pada halaman php map_process.php. 

// Save Marker Function
function save_marker(Marker, mName, mAddress, mType, replaceWin)
{
    //Save new marker using jQuery Ajax
    var mLatLang = Marker.getPosition().toUrlValue(); //get marker position
    var myData = {name: mName, address: mAddress, latlang: mLatLang, type: mType}; //post variables
    console.log(replaceWin);
    $.ajax({
        type: "POST",
        url: "map_process.php",
        data: myData,
        success: function(data) {
            replaceWin.html(data); //replace info window with new html
            Marker.setDraggable(false); //set marker to fixed
            Marker.setIcon('http://localhost:81/mylibs/js/marker/icons/pin_blue.png'); //replace icon
        },
        error: function(xhr, ajaxOptions, thrownError) {
            alert(thrownError); //throw any errors
        }
    });
}

Menampilkan Peta dan Data Marker dari Database

Untuk menampilkan peta google, dia awal kita gunakan function map_initialize, dimana apabila sudah terdapat data marker di database, maka akan bermunculan marker-marker pada peta yang di panggil memalui function $.get("map_process.php",function(){})

function map_initialize()
{
    var googleMapOptions =
            {
                center: mapCenter, // map center
                zoom: 17, //zoom level, 0 = earth view to higher value
                maxZoom: 18,
                minZoom: 16,
                zoomControlOptions: {
                    style: google.maps.ZoomControlStyle.SMALL //zoom control size
                },
                scaleControl: true, // enable scale control
                mapTypeId: google.maps.MapTypeId.ROADMAP // google map type
            };

    map = new google.maps.Map(document.getElementById("google_map"), googleMapOptions);

    //Ambil data XML File, Lihat (map_process.php)
    $.get("map_process.php", function(data) {
        $(data).find("marker").each(function() {
            var name = $(this).attr('name');
            var address = '<p>' + $(this).attr('address') + '</p>';
            var type = $(this).attr('type');
            var point = new google.maps.LatLng(parseFloat($(this).attr('lat')), parseFloat($(this).attr('lng')));
            create_marker(point, name, address, false, false, false, "http://localhost:81/mylibs/js/marker/icons/pin_blue.png");
        });
    });

    //Right Click to Drop a New Marker
    google.maps.event.addListener(map, 'rightclick', function(event) {
        //Edit form to be displayed with new marker
        var EditForm = '<p><div class="marker-edit">' +
                '<form action="ajax-save.php" method="POST" name="SaveMarker" id="SaveMarker">' +
                '<label for="pName"><span>Nama Tempat :</span><input type="text" name="pName" class="save-name" placeholder="Masukan Nama" maxlength="30" /></label>' +
                '<label for="pDesc"><span>Keterangan :</span><textarea name="pDesc" class="save-desc" placeholder="Masukan Alamat" maxlength="90"></textarea></label>' +
                '<label for="pType"><span>Tipe :</span> <select name="pType" class="save-type"><option value="restaurant">Rastaurant</option><option value="bar">Bar</option>' +
                '<option value="house">House</option></select></label>' +
                '</form>' +
                '</div></p><button name="save-marker" class="save-marker">Simpan Marker</button>';

        //Drop a new Marker with our Edit Form
        create_marker(event.latLng, 'New Marker', EditForm, true, true, true, "http://localhost:81/mylibs/js/marker/icons/pin_green.png");
    });

}

PHP Handler

Pada file php, map_process.php, kita lakukan beberapa pemprosesan seperti:
  1. Koneksi database
  2. Menambahkan data marker ketable
  3. Menghapus data marker dari table
  4. Menampilkan data marker dalam format XML

TABLE SQL
CREATE TABLE `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` enum('Restaurant','House','Bar') DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

PHP Script

<?php

// database settings 
$db_username = 'root';
$db_password = '';
$db_name = 'map_marker';
$db_host = 'localhost';
// untuk koneksi database
try {
    mysql_connect($db_host, $db_username, $db_password) or die(mysql_error());
    mysql_select_db($db_name) or die(mysql_error());
} catch (Exception $exc) {
    echo $exc->getTraceAsString();
} 

// Save & delete markers 
if ($_POST) {
// hanya untuk POST request yang dikirim dengan ajax
    $xhr = $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest';
    if (!$xhr) {
        header('HTTP/1.1 500 Error: Request must come from Ajax!');
        exit();
    }

    // dapatkan posisi geospasial data
    $mLatLang = explode(',', $_POST["latlang"]);
    $mLat = filter_var($mLatLang[0], FILTER_VALIDATE_FLOAT);
    $mLng = filter_var($mLatLang[1], FILTER_VALIDATE_FLOAT);

    //Delete Marker
    if (isset($_POST["del"]) && $_POST["del"] == true) {
        $results = mysql_query("DELETE FROM markers WHERE lat=$mLat AND lng=$mLng");
        if (!$results) {
            header('HTTP/1.1 500 Error: Could not delete Markers!');
            exit();
        }
        exit("Done!");
    }

    //validasi data
    $mName = filter_var($_POST["name"], FILTER_SANITIZE_STRING);
    $mAddress = filter_var($_POST["address"], FILTER_SANITIZE_STRING);
    $mType = filter_var($_POST["type"], FILTER_SANITIZE_STRING);
    // menambahkan data ke table
    $results = mysql_query("INSERT INTO markers (name, address, lat, lng, type) VALUES ('$mName','$mAddress',$mLat, $mLng, '$mType')") or die(mysql_error());
    if (!$results) {
        header('HTTP/1.1 500 Error: Could not create marker!');
        exit();
    }

    $output = '<h1 class="marker-heading">' . $mName . '</h1><p>' . $mAddress . '</p>';
    exit($output);
}


//generating Map XML
//Create a new DOMDocument object
$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers"); //Create new element node
$parnode = $dom->appendChild($node); //make the node show up 
// Select all the rows in the markers table
$results = mysql_query("SELECT * FROM markers WHERE 1");
if (!$results) {
    header('HTTP/1.1 500 Error: Could not get markers!');
    exit();
}

//atur document header to text/xml
header("Content-type: text/xml");
// tampilkan dalan XML
while ($obj = mysql_fetch_object($results)) {
    $node = $dom->createElement("marker");
    $newnode = $parnode->appendChild($node);
    $newnode->setAttribute("name", $obj->name);
    $newnode->setAttribute("address", $obj->address);
    $newnode->setAttribute("lat", $obj->lat);
    $newnode->setAttribute("lng", $obj->lng);
    $newnode->setAttribute("type", $obj->type);
}
echo $dom->saveXML();

Untuk melihat hasil demonya bisa dilihat disini. Semoga bermanfaat :-)

 
Bagikan halaman ke sosial media
 
Tags :   googleMaps    marker    php    javascript       

Tentang Penulis

writer hadinug
Web Developer di PT. Yafii Solusi Internasional

Link: http://ysi.co.id

   Komentar Anda