Wednesday, December 31, 2014

Cara Mempercepat Internet Android Tanpa Root

Android menjadi ponsel yang sedang naik daun karena berbagai fitur didalamnya. Mulai dari aktifitas fotografi sampai menjelajah internet dapat dengan mudah dilakukan dengan ponsel Android. Namun ada kalanya pengguna Android tidak puas dengan performa Android miliknya terutama masalah koneksi internet.
Koneksi internet di Android memang tidak selalu cepat, ada kalanya pengguna Android dibuat lebih lama menunggu untuk membuka sebuah halaman web atau mendownload aplikasi di Google Play Store. Namun sebenarnya ada beberapa cara yang bisa kamu lakukan untuk mempercepat koneksi internet di smartphone Android sekaligus mengatasi lag yang kadang terjadi pada ponsel yang berspesifikasi rendah.

Cara Mempercepat Internet Android Tanpa Root

Untuk gadget Android yang belum di root, kamu bisa menerapkan beberapa tips mudah berikut ini.
  1. Matikan dulu jaringan data atau koneksi internet baik GPRS, EDGE, atau koneksi Wifi.
  2. Masuk ke menu setting, aplikasi, lalu pilih aplikasi yang bersangkutan yang paling sering digunakan untuk mengakses internet; browser, aplikasi, atau aplikasi yang lain. Lalu hapus cache-nya.
  3. Atau, bila tak ingin repot gunakan aplikasi CCleaner untuk menghapus dan membersihkan cache dengan satu click mudah.
Screenshot 2014 09 21 08 11 15 300x200 Cara Mempercepat Internet Android
Atau, kalau ponsel kamu mendukung koneksi internet WCDMA, HSDPA, atau HSPA+ atau yang diatas tersebut, bila ingin mendapatkan koneksi internet yang lebih cepat, ubah mode Auto ke koneksi internet tersebut.

Cara Mempercepat Internet Android Root / Aplikasi

1 150x150 Cara Mempercepat Internet Android
Sedangkan untuk sistem Android yang sudah di root hasil yang didapatkan akan lebih maksimal. Cobalah tips mudah berikut ini.
  1. Pastikan Androidmu sudah dalam keadaan rooted.
  2. Download dan install aplikasi Internet Booster (root)
  3. Buka aplikasi tersebut, akan muncul jendela Super User Request, pilih Yes
  4. Lalu centang bagian: Activate Booster dan Auto run.
  5. Aplikasi Internet Booster ini akan mengganti pengaturan pada ROM, untuk mengoptimasi kecepatan internet yang lebih cepat.
*do with your own risk
Baca juga: Cara Menambah RAM Android yang Mudah dan Simpel
Semoga cara mudah mempercepat internet Android diatas bermanfaat. Jangan lupa share, via Facebook, Twitter, atau Google biar teman kamu juga tahu icon smile Cara Mempercepat Internet Android.

plikasi Terbaik Untuk Mempercepat Koneksi Internet Android

Menurut beberapa teman yang menggunakan android murah yang belum memiliki faslitas 3G atau HSDPA, android mereka sangat lamban. Apalagi jika kapasitas RAM yang dimiliki android tersebut masih sangat kecil, yakni kisaran 250 MB. Untuk menjalankan aplikasi saja sudah berat, bagaimana jika buat browsing?

Jika merujuk pada android milik saya, android yang saya gunakan sudah memiliki fasilitas 3G dan HSDPA. Itu saja terkadang masih lambat jika untuk browsing. Dan jika sinyal yang muncul hanya Edge, maka otomatis tidak kuat untuk browsing. Jadi kiranya memang untuj mempercepat koneksi internet, masih dibutuhkan aplikasi penunjang agar internetan makin lancar.
Di play store sendiri sangat banyak aplikasi untuk mempercepat koneksi internet, namun tidak semuanya bagus dan mampu berjalan sesuai yang kita harapkan. Bahkan aplikasi semacam ini dapat memperburuk keadaan android, karena semakin memakan tempat dan memperlambat kinerja android.
Jadi kita memang butuh aplikasi yang terbukti mampu mempercepat koneksi internet android. Seperti beberapa aplikasi berikut ini yang sebaiknyabanda coba:

Mempercepat Koneksi Internet Android

1. Onespeed 6.0.9
Aplikasi ini mampu meningkat kecepatan 10 kali lipat tapi saya pribadi hanya merasakan perubahan 2 kali lipat saja!!! (Dial-up – 10x Faster, Broadband – 5x Faster, Mobile connections – 8x Faster).

2. Flash speed 200%
Mampu mengoptimalkan kecepatan internet anda menjadi 200% atau lebih serta mendukung optimiz Dial-Up, Lan, Cable, ADSL, HDSL, VDSL dan koneksi PPPoE hingga 200%

3.  DSL Speed
Aplikasi DSL Speed ini mampu meningkatkan DSL (misalnya, ADSL, G.lite, IDSL, SDSL) kecepatan koneksi ke MAX.

4. Internet Turbo
Software yang paling sering di gunakan oleh kalangan penguna internet dan mampu mencegah fragmentasi transfer dan mampu meningkatkan transfer data 200-300%

5. Modem Booster
Software ini mampu mempercepat koneksi internet hingga 300% dan sangat cocok untuk pengguna Modem

6. Firefox Ultimate Optimizer
Mozilla merupakan salah satu aplikasi browser terbaik. Untuk mempercepat koneksi internet pada browser ini, sebaiknya anda juga menggunakan aplikasi ini untuk memperkecil RAM pada mozilla firefox

7. Faster Fox
Masih Merupakan Aplikasi Mempercepat Koneksi Internet yang dikhususkan pengguna Web Browser Mozilla Firefox berupa ADD ONS firefox

8. Google Web Accelerator
Kalau software ini belum  Terbukti mempercepat koneksi internet bagi saya karna saya belum memcobaya tapi kata teman-teman saya sih bagus untuk mempercepat koneksi internet.

Cara Sharing Internet Modem/Wifi Melalui Kabel Lan

Artikel ini akan membahas Cara Sharing Internet Wifi/Modem Melalui Kabel Lan, maksudnya apa?, yaitu kita akan membahas tentang cara membagikan internet modem kita melalui kabel agar teman yang memerlukan juga dapat terkoneksi internet, ataupun ketika kita mempunyai koneksi wifi yang bisa internet, sedangkan teman kita tidak bisa, maka disini kita bisa membagikan koneksi wifi tersebut melalui kabel Lan.

cara sharing internet wifi/modem
Langkah2nya sangat mudah, pertama koneksi kan komputernya, lalu lakukan lah sharing, selesai deh :D
Tips Cara Mempercepat Koneksi Internet Gampang !
1. Koneksi kan komputer kamu ke internet melalui modem ataupun wifi, yang penting udah bisa internet, nama koneksi saya yang telah terkoneksi internet adalah Local Area Connection 2
cara sharing internet wifi/modem
2. Koneksi kan komputer kamu dengan komputer lain, jika belum bisa, saya sudah menyiapkan artikelnya, baca aja Cara Koneksikan Komputer ke Komputer Dengan Kabel UTP (Windows ke Windows). Saya telah menyambungkan komputer saya dengan komputer teman, nama koneksi nya adalah Local Area Connection 1.

3. Setelah itu kita akan melalukan sharing, klik Local Area Connection 2 (Koneksi yang terhubung ke internet), Lalu klik Properties, Pilih Tab Sharing yang diatas, lalu ceklis kedua kotak, dan pilih nama koneksi Local yang digunakan untuk menghubungkan kedua komputer, Klik OK OK trus.
cara sharing internet wifi/modem
4. Setelah selesai, seharusnya komputer satu lagi sudah bisa mengakses internet, jika tetap belum bisa maka coba matikan semua firewall.
Inti dari semuanya adalah, jangan salah memilih koneksinya, kamu harus tau koneksi mana yang bisa internet dan koneksi mana yang belum bisa internet.

Jadi jika ingin sharing dari wifi, tinggal buka koneksi wifi lalu setting sharing seperti diatas, begitu juga modem. Sekian artikel Cara Sharing Internet Wifi/Modem Melalui Kabel Lan, baca juga Cara Install Ulang Windows 7 Lengkap+Gambar.

Pengertian dan Fungsi Perintah Ping di CMD

Ping (Packet Internet Groper) adalah program yang dijalankan melalui Command Prompt(CMD) di windows.
Ping biasanya digunakan untuk mengecek apakah sebuah komputer sudah terhubung ke komputer yang di tuju.
Misalnya PC1 telah memasang dan setting kabel menuju PC2, untuk mengeceknya gunakan perintah Ping yang ada di CMD. biasanya jika menggunakan Lan, maka perintah ping di ikuti oleh IP Address komputer tujuan. Pengertian dan Fungsi Perintah Ping di CMD

Berarti, kalau kamu mengetik "Ping google.com" , itu artinya kamu mengecek apakah komputer mu bisa terkoneksi ke server Google ataupun server lain nya di internet.


  • Buka CMD, (tekan Windows+R dan ketikan cmd)
  • Ketikan "ping google.com".
    Pengertian dan Fungsi Perintah Ping di CMD
  • Kalau ada Reply seperti diatas, berarti komputer kamu bisa terkoneksi ke google.
  • Jika Tidak ada Reply dan tulisan nya Request Time Out, berarti komputer kamu belum bisa koneksi ke google.
tambahkan -t agar PC melakukan ping tanpa berhenti, ini untuk mengetahui kalau internetnya mati, berarti Pingnya akan nyangkut.. "ping google.com -t"

Semoga bermanfaat untuk kawan Pengertian dan Fungsi Perintah Ping di CMD,
Artikel lain Cara Koneksikan Komputer ke Komputer Dengan Kabel UTP (Windows ke Windows).
 

Cara Membuat Wireless Tanpa Software di Laptop Windows (Virtual Access Point)

Aduh, ketemu lagi deh di adalahcara.com, kali ini saya ingin membagikan Cara Membuat Wireless Tanpa Software di Laptop Windows (Virtual Access Point), saya membuat wireless di laptop yang bersistem operasi windows 7.

cara membuat wireless tanpa software
Biasanya membuat wireless di laptop itu menggunakan Adhoc dan cara nya agak ribet, karena orang yang mau connect harus menyetting IP terlebih dahulu, yang saya gunakan adalah Virtual Access Point, jadi ketika seseorang terkoneksi ke wireless saya, akan langsung mendapatkan IP (DHCP).

PERSIAPAN :
1. Laptop/Komputer yang memiliki Wireless
2. Koneksi Internet agar perangkat yang terhubung bisa internet.
3. Perangkat lain yang bisa digunakan untuk Connect Wireless.
Tips Cara Mempercepat Koneksi Internet Gampang !
LANGKAH2NYA :
1. Cek dulu apakah wireless kamu support untuk membuat VAP, buka cmd dan ketikan  
netsh wlan show drivers , akan muncul gambar seperti dibawah, jika Hosted Network Supported nya Yes, berarti laptop kamu bisa digunakan.
cara membuat wireless tanpa software

2. Jika belum, ketikan netsh wlan set hostednetwork mode=allow , lalu cek lagi, jika tetap tidak bisa, berarti laptop kamu tidak support.

3. Setting SSid dan password, ketikan netsh wlan set hostednetwork mode=allow ssid=ChrisFerbianto (Nama SSID terserah) key=chrisaja (Password terserah)
Sehingga menjadi netsh wlan set hostednetwork mode=allow ssid=ChrisFerbianto key=chrisaja
cara membuat wireless tanpa software

4. Aktifkan wireless, ketikan netsh wlan start hostednetwork .

5. Akan muncul sebuah Wireless baru dengan nama ChrisFerbianto, bisa di cek langsung dengan perangkat lain. Sampai disini Wireless memang sudah jadi tetapi orang lain belum bisa Connect, saya sudah mengalaminya ketika belum share internet, maka perangkat lain tidak akan mendapatkan IP secara otomatis, tetapi setelah saya share internet ke Wireless, perangkat lain langsung mendapatkan IP address dan bisa langsung berinternetan. Untuk itu mari kita Share internet ke Wireless :p
cara membuat wireless tanpa software
6. Seperti gambar diatas, Local Area 2 adalah koneksi laptop saya ke jaringan agar bisa internet, sedangkan Wireless Network 2 adalah wireless yang tadi kita buat dan belum bisa internet.

7. Klik Local Area 2 (sesuaikan dengan nama koneksi internet kamu), lalu klik properties > pilih tab Sharing > Centang kedua kotak > Pilih nama koneksi wireless kamu, dan klik OK.
cara membuat wireless tanpa software


 8. Pengaturan selesai, coba ulang Connect ke wireless dan pasti akan langsung mendapatkan IP serta langsung internetan. Untuk matiin Wireless nya ketikan netsh wlan stop hostednetwork.
Cara Membuat Wireless Tanpa Software di Laptop Windows
Cukup sudah, capek ngetik euyy, kalo ada yang mw ditanya langsung saja lewat komentar, kalo sempat pasti saya update.

Cara Mengetahui IP Address Sendiri Dengan Mudah

Selamat datang ya, ketemu lagi deh, kamu lagi nyari tau Cara Mengetahui IP Address komputer/laptop ya ? saya akan kasih tau , (padahal gak tau) :p
oke, no basa basi lagi, PERTAMA-TAMA kamu harus tau dulu, IP apa yang mau kamu lihat? IP komputer kita secara lokal atau IP komputer kita yang terhubung ke internet (publik)?
IP publik adalah IP kita yang terhubung ke internet, misalnya kamu buka facebook, maka IP kamu yang berhubungan dengan facebook adalah IP publik, sedang kan IP lokal yaitu IP yang diberikan oleh server lokal kamu, biasanya wifi atau warnet, jadi jangan salah ya..
Langsung kita praktek aja ya, biar langsung ngerti (mudah2an).
IP PUBLIK bisa di lihat dengan cara browsing langsung ke internet, buka browser kamu trus buka aja web untuk mengetahui IP kamu, biasanya saya menggunakan web http://whatismyipaddress.com/
Nah , disitu terlihat bahwa saya menggunakan kartu XL, dan IP saya yang terkoneksi ke internet adalah 112.215.65.156
Cara mempercepat koneksi internet Sekarang kita coba cek IP lokal yang diberikan oleh server ke kamu, kalau IP saya diberikan oleh XL,
Buka cmd kamu, caranya ? untuk windows 7 langsung saja ketikan CMD di menu Start, untuk pengguna XP , klik start > Run > Cmd . lalu ketikan ipconfig dan enter
cara mengetahui ip address
Akan keluar banyak teks, scroll ke atas dan akan ada terlihat IP lokal kita, disini IP lokal saya adalah 10.226.67.71
Jadi misalnya kita buka facebook, data dari facebook pertama dikirim ke server XL dulu, baru di transfer ke kita, Udah paham kan ?, begitu deh Cara Mengetahui IP Address Komputer sendiri.

Cara Backup Driver Windows Dalam 5 Menit !

Cara Backup Driver
Haloo, kali ini saya akan share Cara Backup Driver Windows Dalam 5 Menit ! , Loh emang bisa ?
Yah bisalah, biasanya yang ingin install windows 7 sendiri lupa backup driver sehingga ketika selesai install windows, mereka harus mencari dan mendownload ulang driver yang dibutuhkan sesuai Tipe Komputer/Laptopnya.

Nah, untuk mengatasi hal tersebut, kita harus backup driver agar pada saat selesai Menginstall windows 7, tinggal update driver, selesai, enak kan?

Saya menggunakan aplikasi DriverMax , software sebesar 7MB bisa menghemat untuk download driver ratusan MB , oke deh, tanpa basa-basi lagi, langsung download aja aplikasinya

Download Via Softpedia ,,

  • Lalu install drivermax nya, tinggal dibuka lalu klik next2 doang kok, terakhirnya finish.
  • Setelah Finish drivermax akan terbuka sendiri, lalu klik tab "backup driver" yang di atas , secara otomatis drivermax akan scan driver yang terinstall di laptop/komputer anda,
  • Backup aja semuanya , klik backup yang dibawah lalu pilih "backup all driver", 
  • Setelah selesai, akan muncul folder yang isinya file backup dalam bentuk .rar, copy file tersebut ke local disk D: atau yang lain agar tidak ikut terformat.
Backup Selesai ! Gampangkan Cara Backup Driver
Jika anda ingin menginstall windows, saya telah menyediakannya juga, lengkap + gambar, Cara Install Ulang Windows 7 Lengkap+Gambar ,

Lalu gmna cara install Driver yang udah di backup ? , Tenang, saya juga telah menyediakan caranya, buka aja nih

Cara Mempercepat Koneksi Internet Android, WIFI dan SPEEDY

Masterz Seo - Cara dan tips mempercepat koneksi internet pada perangkat Android, speedy dan wifi dengan mudah. Dijaman yang serba modern ini kebutuhan akan koneksi internet seakan akan telah menjadi salah satu kebutuhan pokok setiap orang. Di Indonesia sendiri telah tercatat sekitar 50 juta lebih pengguna internet dan terus berkembang tiap tahunya. Berawal hanya sekedar tempat mengakses hiburan dan informasi sekarang dunia internet mulai banyak digunakan untuk bisnis, seperti berjualan, promosi produk dan jasa melalui jajaring sosial dan website. Ngomong-ngomong masalah bisnis lewat internet ane punya kabar terbaru nich,, syaratnya cukup mudah kok cuma pake hape android doang, jika agan-agan tertarik langsung aja menuju artikel sebelumnya : Cara Memulai Bisnis Online Tanpa Modal Dengan Android .
Pada artikel tersebut sudah saya jelaskan secara detail panduan untuk mendaftar dan menghasilkan dolar dari android.

   Aduh maaf ya sedikit melenceng dari topik yang mau dibahas, oke deh sob langsung aja ke TKP. Pada artikel kali ini saya ingin berbagi tutorial cara mempercepat koneksi internet Android, Speedy dan juga Wifi dan simaklah tips berikut ini.

1. Cara Mempercepat Koneksi Internet Android

   Pada umumya koneksi internet android anda lambat dikarenakan provider yang anda gunakan kurang bagus, karena memang belakangan ini provider GSM di Indonesia layanannya internetnya sangat kurang memuaskan, apalagi penggunaanya sekitar jam 18.00 -22.00 Wib. Jadi jika koneksi internet android anda lelet pada jam jam tersebut berarti kita senasib..he..he...
Tapi ada juga kasus lain padahal provider yang digunakan udah bagus, hapenya juga bagus tapi kok masih lola juga ...ha...ha... Kalau menurut saya penyebabnya ponsel anda terlalu banyak menyimpan file sampah atau Chace, karena memang file-file sampah jika dibiarkan menumpuk dapat memberatkan kinerja android anda jadi harus segera dihapus. Namun untuk proses penghapusan Chace memang agak sulit karena letaknya yang tidak menentu dan tersembunyi. Untuk menghapus chace secara tuntas anda perlu menginstal aplikasi pembersih chace dan aplikasi pembersih file sampah terbaik yang saya ketahui adalah DU Speed Booster (Cleaner) , selain sebagai pembersih Chace aplikasi ini juga sangat efiktif dalam meningkatkan kinerja android anda hingga 60% serta meningkatkan ruang penyimpanan pada kartu SD.
Untuk membuktikannya silakan download di sini : https://play.google.com/store/apps/details?id=com.dianxinos.optimizer. duplay


Cara Mempercepat koneksi internet android

Setelah aplikasi tersebut anda download buka dan jalankan aplikasinya, dan silakan lihat perbedaanya.


2. Cara memaksimalkan kecepatan internet Telkom Speedy

   Karena saya bukan pengguna telkom speedy jadi saya tidak tau pasti apakah tips di bawah ini berhasil atau tidak namun jika anda belum berhasil anda bisa mencoba trik yang lain.
  Cara Pertama :
  • Masuk ke settingan modem, 192.168.1.1
  • Klik Advanced Setup
  • Klik ADSL, lalu pilih ADSL Mode, awalnya pasti ADSL2+ lalu anda ganti dengan G.DMT, kemudian klick save, Tunggu beberapa saat browsing lagi
  Cara Kedua:
  • Jika anda sudah lakukan cara-cara diatas, masuklah ke control panel dan pilih Network Connections
  • Klik kanan di LAN dan pilih properties. Tergantung kalian pake LAN atau WIFI
  • Kemudian klik diinternet protocol (TCP/IP) dan klik properties
  • Lalu pilih Use the following DNS server addresses
  • Masukkan preferred DNS server: 8.8.8.8
  • Masukkan Alternate DNS server :8.8.4.4
  • Setelah itu klick ok
  • Lalu klik kanan di gambar jaringan di paling bawah kanan layar komputer anda kemudian pilih repair. Jika sudah selesai anda bisa membandingkan dari kecepatan internet anda yang sebelumnya.
Cara mempercepat koneksi internet WIFI

1. Pastikan anda sedang berada pada jangkauan area WIFI, kemudian koneksikan komputer anda pada jaringan wifi. Setelah itu klik kanan pada nama jaringan lalu pilih Status, lihat gambar di bawah ini.

cara mempercepat koneksi internet wifi















2. Setelah anda  menjalankan hal diatas maka akan muncul Status Wireles Network Connection lalu klick Detail
 status, lihat gamabar.

tip meningkatkan kecepatan internet wifi

















3. Catat angka yang  dilingkari berwarna meras seperti pada gambar di atas.
4. Klick Start ► Run Ketik cmd.exe   (Windows + R untuk win 7)
5. Ketikkan teks ini ping -l 500 192.168.1.1 –t kemudian tekan Enter.
tujuan dilakukan hal tersebut adalah anda meminta bandwitch sebanyak 500 bytes dari server jaringan hotspot. Bandwitch normal yang diberikan biasanya hanya 32 bytes per-user tetapi dengan mengetikkan format diatas berarti anda meminta 500 bytes, tetapi jika anda belum puas anda bisa menambahkannya sampai 1000, 2000, 3000 sapai 6000 pada angka 500 itu.
192.168.1.1 adalah IP address dari jaringan hotspot yang saya gunakan.
Biarkan jendela cmd terbuka selama anda internetan.

agar koneksi internet wifi cepat










Silakan praktekkan cara-cara diatas semoga bisa menambah kecepatan internet anda, Demikian penjelasan saya mengenai Cara mempercepat koneksi internet Android WIFI dan SPEEDY, terimakasih telah berkunjung dan semoga artikel ini bermanfaat buat anda.

Tuesday, December 30, 2014

jQuery and Google Maps #2: AJAX Storing and Retrieving Points

Continuing the series on jQuery and Google Maps, I will teach you how to store and retrieve points with using AJAX and a server-side language. This tutorial will use PHP/MySQL on the server, but it is basic enough that re-writing in another language should not be difficult.

View Final Demo

First, let me share with you the design-pattern behind the tutorial. My design pattern has two steps. The first is to use a simple HTML form to create new locations by posting the data to the server via AJAX. The second step is to fetch those locations from the server also via AJAX. Sound simple? Well, then lets get started…
Note: This tutorial builds on the first tutorial’s code, so all code I am showing you here will be added onto it.

Step #1: Create the, “Add Location” Form

To allow users to add locations to the map, let’s create a basic form. This will include the parts of an address, as well as the name of the location.

<form id="add-point"action="map-service.php"method="POST">
  <input type="hidden"name="action"value="savepoint"id="action">
  <fieldset>
    <legend>Add a Point to the Map</legend>
    <div class="error" style="display:none;"></div>
    <div class="input">
      <label for="name">Location Name</label>
      <input type="text"name="name"id="name"value="">
    </div>
    <div class="input">
      <label for="address">Address</label>
      <input type="text"name="address"id="address"value="">
    </div>
    <button type="submit">Add Point</button>
  </fieldset>
</form>
A couple things to note about the form:
  • The form’s action is pointed to map-service.php, which is where we will process the form data.
  • A hidden input <input type="hidden"name="action"value="savepoint"id="action"> will be used on the server to flag that we want to save a point to the database. This is just a personal preference on how to do things, there are many other ways to flag the intended action.
  • An empty div with class error <div class="error"style="display:none;"></div> is placed in the form to be used in a later step to display errors.

Step #2: Add Styles to the Form

By adding a few CSS rules to our page, we will set our form next to the map and spruce up the form a bit.

#add-point { float:left; } 
div.input { padding:3px 0; } 
label { display:block; font-size:80%; } 
input, select { width:150px; } 
button { float:right; } 
div.error { color:red; font-weight:bold; }

Step #3: Geoencode Address Before Submiting Data

3a) Override default form submit

At this point we’ll override the form’s default submit action by selecting the form $("#add-point") , then using jQuery’s submit event method . This method accepts a function that will run on submit of the form.

$("#add-point").submit(function(){ 
  geoEncode(); 
  return false; 
});

3b) Add GeoCoder

Then, inside the submit we will post the form data with AJAX using jQuery’s ajax post method .

var geo = new GClientGeocoder(); 
var reasons=[]; 
reasons[G_GEO_SUCCESS] = "Success"; 
reasons[G_GEO_MISSING_ADDRESS] = "Missing Address"; 
reasons[G_GEO_UNKNOWN_ADDRESS] = "Unknown Address."; 
reasons[G_GEO_UNAVAILABLE_ADDRESS] = "Unavailable Address"; 
reasons[G_GEO_BAD_KEY] = "Bad API Key"; 
reasons[G_GEO_TOO_MANY_QUERIES] = "Too Many Queries"; 
reasons[G_GEO_SERVER_ERROR] ="Server error";

3c) Get geocode from address


function geoEncode() { 
  var address = $("#add-point input[name=address]").val(); 
  geo.getLocations(address, function (result){ 
    if (result.Status.code == G_GEO_SUCCESS) { 
      geocode = result.Placemark[0].Point.coordinates; savePoint(geocode); 
    } else { 
      var reason="Code"+result.Status.code; 
      if (reasons[result.Status.code]) { 
        reason = reasons[result.Status.code] 
      } 
      $("#add-point .error").html(reason).fadeIn(); 
      geocode = false; 
    } 
  }); 
}

Step #4: Submit Data to Server


function savePoint(geocode) { 
  var data = $("#add-point :input").serializeArray(); 
  data[data.length] = { name:"lng", value: geocode[0] }; 
  data[data.length] = { name:"lat", value: geocode[1] }; 
  $.post($("#add-point").attr('action'), data, function(json){ 
    $("#add-point .error").fadeOut(); 
    if (json.status =="fail") { 
      $("#add-point .error").html(json.message).fadeIn(); 
    }
    if (json.status =="success") { 
      $("#add-point :input[name!=action]").val(""); 
      var location = json.data; addLocation(location); zoomToBounds(); 
    } 
  }, "json"); 
}
The $.post method accepts parameters.
  1. URL to post data to: $(this).attr('action') will get the action attribute from the form that was submitted in the previous step.
  2. Data in name, value pairs i.e. { name:"inputname", value:"inputvalue"} we will get all the inputs using the :input selector in jQuery, then use the serialize array function to turn those inputs into name, value pairs. Then add the two geocode name/value pairs to the data object.
  3. Function to run after AJAX response is received. This function has one parameter which contains the response of the AJAX request.
  4. Type of data to be returned (optional). In this case we will use JSON.

Step #5: Use PHP on the Server to Process the Form

Once the data is posted with jQuery, we can handle it on the server with PHP.

5a) Check the action and validate the name

Let’s simply check if the action variable is posted as,“savepoint”. Then validate that the name has the proper characters with a regular expression and also that it is not empty. If any data is invalid, let’s call a fail method (defined in next sub-step) with the message we want to show to the user.

<?php if ($_POST['action'] == 'savepoint') { 
  $name = $_POST['name']; 
  if(preg_match('/[^ws]/i', $name)) { 
    fail('Invalid name provided.'); 
  } 
  if(empty($name)) { 
    fail('Please enter a name.'); 
  } 
} ?>
Save the file as map-service.php or whatever you named your form’s action attribute.

5b) Output the error message as a JSON object

Our fail function will use PHP’s die method to stop the script from executing and output an error message to the client. Since the front-end (jQuery) is expecting a JSON object, we want to make sure to always send back a JSON response. To output JSON with PHP, you simply pass an array into the json encode method (json_encode is PHP 5.2+ only, if you are using less than 5.2 then use the JSON PHP library ).

function fail($message) { 
  die(json_encode(array('status' => 'fail', 'message' => $message))); 
}
For the JSON array we want to use the JSEND specification for sending back a response. Basically, you have a key/value pair of status equals success or fail. That way the response can easily be checked on the front-end. I’m deviating from the JSEND spec a little bit by only sending a string back instead of a key/value pair of messages.
Using Firebug and Firefox , we can inspect the Ajax requests easily within the browser.

You can see here I submitted the form without entering a name and it sent me back an error message in the form of JSON.

Step #6: Display the Error Messages with jQuery

Hopping back to the jQuery code, we will write the error handling.
Inside the post code, we will first use the hide method to hide the error div in case it is already displaying. Then check if json.status is showing,“fail”. If it is, we’ll place the json.message inside the error div with jQuery’s html attribute method and then fade it in with the fade in method .

$("#add-point .error").hide(); 
if (json.status =="fail") { 
  $("#add-point .error").html(json.message).fadeIn(); 
}

Step #7: Create a Database and Store the Locations

Using SQL, create a database table named locations which has a“name”,“latitude”,“longitude“and an“id“in it. If you need help with this, you will have to consult w3schools php and mysql for more help.

7a) Create the table with SQL


CREATE TABLE `locations` ( 
  `id` int(11) unsigned NOT NULL auto_increment, 
  `name` varchar(100) default NULL, 
  `lat` float(15,11) default NULL, 
  `lng` float(15,11) default NULL, 
  PRIMARY KEY (`id`) 
)

7b) Insert name and location into the database with PHP and MySQL

We will use PHP and MySQL to insert the new location into the database. Directly after, we will either flag a success or fail message to the user.

$query ="INSERT INTO locations SET name='$_POST[name]', lat='$lat', lng='$lng'"; 
$result = map_query($query); 
if ($result) { 
  success(array('lat' =>$_POST['lat'], 'lng' =>$_POST['lng'], 'name' =>$name)); 
} else { 
  fail('Failed to add point.'); 
}
If you noticed, I created a custom function called map_query to abstract out the database stuff. Here is the function definition. Make sure to update the,“MYSQL“stuff with your credentials.

function map_query($query) { 
  mysql_connect('MYSQL_HOST', 'MYSQL_USER', 'MYSQL_PASSWORD') OR die(fail('Could not connect to database.')); 
  mysql_select_db ('MYSQL_DATABASE'); return mysql_query($query); 
}
I also created a similar method to“fail“called“success“which looks like:

function success($data) { 
  die(json_encode(array('status' =>'success', 'data' =>$data))); 
}
An example of a succesful response in firebug:

Step #8: Map the New Point

Going back to the jQuery code, we can now add the success response handling. The response is a JSON object with“lat”,“lng“and“name“properties. I’ll give you the code inside the success handling, then later show you what each custom function is doing.

if (json.status =="success") { 
  $("#add-point :input[name!=action]").val(""); 
  var location = json.data; 
  addLocation(location); 
  zoomToBounds(); 
}
After a location is successfully added to the database, we want to clear the form to prevent duplicate entry. Do this by selecting the inputs with the :input selector. Then we need to filter out theaction input, do this by using the attribute not equal selector [name!=action] .
My addLocation(location) function is simply our code from the last tutorial placed into a function to be reusable later.

function addLocation(location) { 
  var point = new GLatLng(location.lat, location.lng); 
  var marker = new GMarker(point); 
  map.addOverlay(marker); 
  bounds.extend(marker.getPoint()); 
  $("<li />")
    .html(location.name) 
    .click(function(){ 
      showMessage(marker, location.name); 
    }) 
    .appendTo("#list"); 
  GEvent.addListener(marker,"click", function(){ 
    showMessage(this); 
  }); 
}
It has a few things you might want to note:
  • using location.name, location.lat and location.lng means that we will be passing in a location object with those properties to the function.
  • Ignore bounds.extend(marker.getPoint()); and zoomToBounds for now or skip to
  1. quickly to find out what they do.

Step #9: Load and Display the Locations from in the Database

When the page initially loads, we want to load all of our stored points. The simplest way to do this (in my opinion) is to do a GET request to fetch a JSON object from the server after the page loads.
To make a,“GET“request to the server, we can use jQuery’s getJson method . We will send the server a,“get“variable called action with value,“listpoints”.

$.getJSON("php/map-service.php?action=listpoints", function(json) { 
  // do stuff in step #11 
});

Step #10: Get the Locations from the Database

Simply check the,“GET“action in the PHP and run this code to fetch the locations records. Pretty straight-forward code here. We are creating an array of points and then sending them back to the client as JSON.

if ($_GET['action'] == 'listpoints') { 
  $query ="SELECT * FROM locations"; 
  $result = map_query($query); 
  $points = array();
  while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { 
    array_push($points, array('name' =>$row['name'], 'lat' =>$row['lat'], 'lng' =>$row['lng'])); 
  } 
  echo json_encode(array("Locations"=>$points)); 
  exit; 
}

Step #11: Display the Locations

Iterate through the JSON object that contains the locations inside the getJson response function.

if (json.Locations.length>0) { 
  for (i=0; i<json.Locations.length; i++) { 
    var location = json.Locations[i]; 
    addLocation(location); 
  } 
  zoomToBounds(); 
}
Here we are simply looping through the Locations inside the json object and calling out addLocation method.

Step #12: Zoom Map to Show all Points

Let’s define that mysterious zoomToBounds method that I keep calling and not telling you what it does.
First, define a variable called,“bounds“above the getJson method.

var bounds = new GLatLngBounds();
Note that in step #8’s addLocation method we are extending the bounds with bounds.extend(marker.getPoint()); This takes the bounds and adds each point to it. Then we can set the map to show all the points later by using the bounds that contains each point on the map.

function zoomToBounds() { 
  map.setCenter(bounds.getCenter()); 
  map.setZoom(map.getBoundsZoomLevel(bounds)-1); 
}
This function sets the center of the map, and the zoom minus 1 to set the map’s viewport based on that bounds variable we declared and extended earlier.
Congrats! You just create a Google Maps mashup that you can add and remove points to dynamically with Ajax, PHP and MySQL.

sing PHP and MySQL to create KML

This tutorial is intended for developers who are familiar with PHP and MySQL and want to learn how to generate KML from a MySQL database. For this tutorial, you will be creating two scripts that dynamically generate KML from a database of locations in Seattle. The first script creates a collection of points, with two types of places—restaurants and bars—delineated by distinguishing icons. When the user clicks a marker, a balloon displays name and address information. The second script creates a line that connects all the restaurants. The tutorial also shows how to create a Google Map that displays the KML files and a NetworkLink file that points to the KML file and enables the user to open it in Google Earth.
This tutorial is based on the article Using PHP/MySQL with Google Maps written by Pamela Fox, which shows how to export data from a MySQL table to Google Maps using PHP. You can skip the first two steps of this tutorial if you have read Pamela's article. The remainder of the tutorial is significantly different since it deals with KML.
The tutorial is broken up into the following steps:
  1. Creating the table
  2. Populating the table
  3. Using PHP to output KML
  4. Displaying your KML Files
  5. Where to go from here
Image of Google Earth

Step 1: Creating the table

When you create the MySQL table, you want to pay particular attention to the lat and lng attributes. With the current zoom capabilities of Google Maps, you should need only 6 digits of precision after the decimal. To keep the storage space required for our table at a minimum, you can specify that the lat and lng attributes are floats of size (10,6). That will let the fields store 6 digits after the decimal, plus up to 4 digits before the decimal, e.g. -123.456789 degrees. Your table should also have an id attribute to serve as the primary key, and a type attribute to distinguish between restaurants and bars.
Note: This tutorial uses location data that already has latitude and longitude information needed to plot corresponding markers. If you're trying to use your own data that doesn't yet have that information, use a batch geocoding service to convert the addresses into latitudes/longitudes. Some sites make the mistake of geocoding addresses each time a page loads, but doing so results in slower page loads and unnecessary repeat geocodes. It's always better to hard-code the latitude/longitude information when possible.
You can create the table data in one of two ways—either using the phpMyAdmin interface or using SQL commands. Here's how you would create the table using the phpMyAdmin interface.
Here's the corresponding SQL statement that creates the table. phpsqlajax_createtable.sql:
CREATE TABLE 'markers' (
 'id' INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
 '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
) ENGINE = MYISAM ;


Step 2: Populating the table

After creating the table, it's time to populate it with data. Sample data for 10 Seattle places is provided below. In phpMyAdmin, you can use the IMPORT tab to import various file formats, including CSV (comma-separated values). Microsoft Excel and Google Spreadsheets both export to CSV format, so you can easily transfer data from spreadsheets to MySQL tables through exporting/importing CSV files.
Here's the sample data in CSV format. phpsqlajax_data.csv:
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
Here's a screenshot of the import options used to transform this CSV into table data:
Here are the corresponding SQL statements. phpsqlajax_data.sql:
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');


Step 3: Using PHP to output KML

At this point, you should have a table named "markers" filled with sample data. You now need to write some PHP statements to export the table data into a KML format. If you've never written PHP to connect to a MySQL database, you should visit php.net and read up on mysql_connect, mysql_select_db, my_sql_query, and mysql_error.
You should put your database connection information in a separate file. This is generally a good idea whenever you're using PHP to access a database, as it keeps your confidential information in a file that you won't be tempted to share. In the Maps API forum, we've occasionally had people accidentally publish their database connection information when they were just trying to debug their code. The file should look like this, but with your own database information filled in. phpsqlajax_dbinfo.php:
<?
 $username = 'username';
 $password = 'password';
 $database = 'database';
 $server = 'server'
?>

Using PHP5's DOM functions to output KML

Here's where the new stuff starts. In Pamela Fox's earlier article, she presented PHP 4 code that used the dom_xml extension to create a simple markers file that was later parsed using JavaScript. For this tutorial, you want to produce KML. Instead of going through JavaScript, you can specify Placemark styling directly in KML. This tutorial will show code that uses both PHP 5's integrated DOM libraries, and the PHP 4 dom_xml extension.
First, check your configuration or try initializing a DOMDocument() to determine if your server's PHP has DOM functionality on. If you do have access to the DOM, you can use it to create XML nodes, append child nodes, and output an XML document. Since KML is an XML markup language, this works for KML as well. If DOM is not available on your server, try using either the dom_xml or echo method described below.
Once you've determined that you can continue with DOM, start by creating different placemarks for each row in the markers table. In PHP, initialize a new XML document and create the "kml" parent node. Add the KML namespace as an attribute. After creating the basic structure of a KML <document> element, construct the two styles—one for restaurants and one for bars—that will later be referenced by Placemarks through the <styleUrl> element.
Next, connect to the database, execute a SELECT * (select all) query on the markers table, and iterate through the results. For each row in the table (each location), create a new <Placemark> element. Extract information from the row and use it to create child elements of the <Placemark>, <name>, <description>, <styleUrl>, and <Point>. Assign the <styleUrl> element a value depending on the value of the type column for that row. Then give the <Point> element a child element <coordinates>, and combine the values of the lng and lat columns as its value.
The PHP file below creates a KML file with the proper HTML headers. It assigns the value of the name column to the <name> element, and the value of the address to the <description> element. After generating the KML from this script, you should verify the results with a text editor or browser. phpsql_genkml.php:
<?php
require('phpsqlajax_dbinfo.php');

// Opens a connection to a MySQL server.

$connection = mysql_connect ($server, $username, $password);

if (!$connection) 
{
  die('Not connected : ' . mysql_error());
}
// Sets the active MySQL database.
$db_selected = mysql_select_db($database, $connection);

if (!$db_selected) 
{
  die('Can\'t use db : ' . mysql_error());
}

// Selects all the rows in the markers table.
$query = 'SELECT * FROM markers WHERE 1';
$result = mysql_query($query);

if (!$result) 
{
  die('Invalid query: ' . mysql_error());
}

// Creates the Document.
$dom = new DOMDocument('1.0', 'UTF-8');

// Creates the root KML element and appends it to the root document.
$node = $dom->createElementNS('http://earth.google.com/kml/2.1', 'kml');
$parNode = $dom->appendChild($node);

// Creates a KML Document element and append it to the KML element.
$dnode = $dom->createElement('Document');
$docNode = $parNode->appendChild($dnode);

// Creates the two Style elements, one for restaurant and one for bar, and append the elements to the Document element.
$restStyleNode = $dom->createElement('Style');
$restStyleNode->setAttribute('id', 'restaurantStyle');
$restIconstyleNode = $dom->createElement('IconStyle');
$restIconstyleNode->setAttribute('id', 'restaurantIcon');
$restIconNode = $dom->createElement('Icon');
$restHref = $dom->createElement('href', 'http://maps.google.com/mapfiles/kml/pal2/icon63.png');
$restIconNode->appendChild($restHref);
$restIconstyleNode->appendChild($restIconNode);
$restStyleNode->appendChild($restIconstyleNode);
$docNode->appendChild($restStyleNode);

$barStyleNode = $dom->createElement('Style');
$barStyleNode->setAttribute('id', 'barStyle');
$barIconstyleNode = $dom->createElement('IconStyle');
$barIconstyleNode->setAttribute('id', 'barIcon');
$barIconNode = $dom->createElement('Icon');
$barHref = $dom->createElement('href', 'http://maps.google.com/mapfiles/kml/pal2/icon27.png');
$barIconNode->appendChild($barHref);
$barIconstyleNode->appendChild($barIconNode);
$barStyleNode->appendChild($barIconstyleNode);
$docNode->appendChild($barStyleNode);

// Iterates through the MySQL results, creating one Placemark for each row.
while ($row = @mysql_fetch_assoc($result))
{
  // Creates a Placemark and append it to the Document.

  $node = $dom->createElement('Placemark');
  $placeNode = $docNode->appendChild($node);

  // Creates an id attribute and assign it the value of id column.
  $placeNode->setAttribute('id', 'placemark' . $row['id']);

  // Create name, and description elements and assigns them the values of the name and address columns from the results.
  $nameNode = $dom->createElement('name',htmlentities($row['name']));
  $placeNode->appendChild($nameNode);
  $descNode = $dom->createElement('description', $row['address']);
  $placeNode->appendChild($descNode);
  $styleUrl = $dom->createElement('styleUrl', '#' . $row['type'] . 'Style');
  $placeNode->appendChild($styleUrl);

  // Creates a Point element.
  $pointNode = $dom->createElement('Point');
  $placeNode->appendChild($pointNode);

  // Creates a coordinates element and gives it the value of the lng and lat columns from the results.
  $coorStr = $row['lng'] . ','  . $row['lat'];
  $coorNode = $dom->createElement('coordinates', $coorStr);
  $pointNode->appendChild($coorNode);
}

$kmlOutput = $dom->saveXML();
header('Content-type: application/vnd.google-earth.kml+xml');
echo $kmlOutput;
?>

Using PHP 4's dom_xml to output KML

PHP 4's dom_xml functions are very similar to PHP 5's DOM. phpsql_genkml2.php:
<?php
require('phpsqlajax_dbinfo.php');

// Opens a connection to a MySQL server.
$connection=mysql_connect ($server, $username, $password);
if (!$connection) 
{
  die('Not connected : ' . mysql_error());
}
// Sets the active MySQL database.
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) 
{
  die ('Can\'t use db : ' . mysql_error());
}

// Selects all the rows in the markers table.
$query = 'SELECT * FROM markers WHERE 1';
$result = mysql_query($query);
if (!$result) 
{
  die('Invalid query: ' . mysql_error());
}

// Creates the Document.
$dom = new domxml_new_doc('1.0');

// Creates the root KML element and appends it to the root document.
$node = $dom->create_element_ns('http://earth.google.com/kml/2.1', 'kml');
$parNode = $dom->append_child($node);

// Creates a KML Document element and append it to the KML element.
$dnode = $dom->create_element('Document');
$docNode = $parNode->append_child($dnode);
 
//Creates the two Style elements, one for restaurant and one for bar, and append the elements to the Document element.
$restStyleNode = $dom->create_element('Style');
$restStyleNode->set_attribute('id', 'restaurantStyle');
$restIconstyleNode = $dom->create_element('IconStyle');
$restIconstyleNode->set_attribute('id', 'restaurantIcon');
$restIconNode = $dom->create_element('Icon');
$restHref = $dom->create_element('href', 'http://maps.google.com/mapfiles/kml/pal2/icon63.png');
$restIconNode->append_child($restHref);
$restIconstyleNode->append_child($restIconNode);
$restStyleNode->append_child($restIconstyleNode);
$docNode->append_child($restStyleNode);
$barStyleNode = $dom->create_element('Style');
$barStyleNode->set_attribute('id', 'barStyle');
$barIconstyleNode = $dom->create_element('IconStyle');
$barIconstyleNode->set_attribute('id', 'barIcon');
$barIconNode = $dom->create_element('Icon');
$barHref = $dom->create_element('href', 'http://maps.google.com/mapfiles/kml/pal2/icon27.png');
$barIconNode->append_child($barHref);
$barIconstyleNode->append_child($barIconNode);
$barStyleNode->append_child($barIconstyleNode);
$docNode->append_child($barStyleNode);

// Iterates through the MySQL results, creating one Placemark for each row.
while ($row = @mysql_fetch_assoc($result))
{
  // Creates a Placemark and append it to the Document.
  $node = $dom->create_element('Placemark');
  $placeNode = $docNode->append_child($node);
  // Creates an id attribute and assign it the value of id column.
  $placeNode->set_attribute('id', 'placemark' . $row['id']);

  // Create name, and description elements and assigns them the values of the name and address columns from the results.
  $nameNode = $dom->create_element('name',htmlentities($row['name']));
  $placeNode->append_child($nameNode);
  $descNode = $dom->  create_element('description', $row['address']);
  $placeNode->append_child($descNode);
  $styleUrl = $dom->create_element('styleUrl', '#' . $row['type'] . 'Style');
  $placeNode->append_child($styleUrl);
 // Creates a Point element.
  $pointNode = $dom->create_element('Point');
  $placeNode->append_child($pointNode);
   
  // Creates a coordinates element and gives it the value of the lng and lat columns from the results.
  $coorStr = $row['lng'] . ','  . $row['lat'];
  $coorNode = $dom->create_element('coordinates', $coorStr);
  $pointNode->append_child($coorNode);
}

$kmlOutput = $dom->dump_mem(TRUE, 'UTF-8');
header('Content-type: application/vnd.google-earth.kml+xml');
echo $kmlOutput;
?>
As you can see, most of the differences are solved by turning the camel case (createElement) functions into all lower case with an underscore ("_") to separate the words in the function name. The exception to that rule is domxml_new_doc, which PHP 5 replaces with DOMDocument. Also, using dom_xml, you set the encoding when you dump the file to memory, not when you create the file.

Using PHP's echo to output KML

If you don't have access to PHP's DOM functions, then you can simply output the KML with the echo function.
  1. Connect to the database and execute the SELECT * (select all) query on the markers table.
  2. Create an array of strings that make up the basic structure of the KML document.
  3. Then iterate through the query results, adding an element to the array for each row in the table (each location).
  4. Create the Placemark element for that row, passing the name column through the htmlentities function in case there are any special entities in them.
  5. Finish the script by joining the array into one big string, echoing out the headers, and then echoing out the KML string.
The PHP file that does all this is shown below. phpsql_genkml3.php:
<?php
require('phpsqlajax_dbinfo.php');

 // Opens a connection to a MySQL server.
$connection = mysql_connect ($server, $username, $password);
if (!$connection) 
{
  die('Not connected : ' . mysql_error());
}

// Sets the active MySQL database.
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) 
{
  die ('Can\'t use db : ' . mysql_error());
}

 // Selects all the rows in the markers table.
 $query = 'SELECT * FROM markers WHERE 1';
 $result = mysql_query($query);
 if (!$result) 
 {
  die('Invalid query: ' . mysql_error());
 }

// Creates an array of strings to hold the lines of the KML file.
$kml = array('<?xml version="1.0" encoding="UTF-8"?>');
$kml[] = '<kml xmlns="http://earth.google.com/kml/2.1">';
$kml[] = ' <Document>';
$kml[] = ' <Style id="restaurantStyle">';
$kml[] = ' <IconStyle id="restuarantIcon">';
$kml[] = ' <Icon>';
$kml[] = ' <href>http://maps.google.com/mapfiles/kml/pal2/icon63.png</href>';
$kml[] = ' </Icon>';
$kml[] = ' </IconStyle>';
$kml[] = ' </Style>';
$kml[] = ' <Style id="barStyle">';
$kml[] = ' <IconStyle id="barIcon">';
$kml[] = ' <Icon>';
$kml[] = ' <href>http://maps.google.com/mapfiles/kml/pal2/icon27.png</href>';
$kml[] = ' </Icon>';
$kml[] = ' </IconStyle>';
$kml[] = ' </Style>';

// Iterates through the rows, printing a node for each row.
while ($row = @mysql_fetch_assoc($result)) 
{
  $kml[] = ' <Placemark id="placemark' . $row['id'] . '">';
  $kml[] = ' <name>' . htmlentities($row['name']) . '</name>';
  $kml[] = ' <description>' . htmlentities($row['address']) . '</description>';
  $kml[] = ' <styleUrl>#' . ($row['type']) .'Style</styleUrl>';
  $kml[] = ' <Point>';
  $kml[] = ' <coordinates>' . $row['lng'] . ','  . $row['lat'] . '</coordinates>';
  $kml[] = ' </Point>';
  $kml[] = ' </Placemark>';
 
} 

// End XML file
$kml[] = ' </Document>';
$kml[] = '</kml>';
$kmlOutput = join("\n", $kml);
header('Content-type: application/vnd.google-earth.kml+xml');
echo $kmlOutput;
?>

Checking that the KML output works

Call this PHP script from the browser to make sure it's producing valid KML. If the script is working correctly, the KML output looks like this. phpsqlkml_expectedoutput.kml:
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns = "http://earth.google.com/kml/2.1">
  <Document>
    <Style id="restaurantStyle">
      <IconStyle id="restuarantIcon">
      <Icon>
        <href>http://maps.google.com/mapfiles/kml/pal2/icon63.png</href>
      </Icon>
      </IconStyle>
    </Style>
    <Style id="barStyle">
      <IconStyle id="barIcon">
      <Icon>
        <href>http://maps.google.com/mapfiles/kml/pal2/icon27.png</href>
      </Icon>
      </IconStyle>
      </Style>
    <Placemark id="placemark1">
      <name>Pan Africa Market</name>
      <description>1521 1st Ave, Seattle, WA</description>
      <styleUrl>#restaurantStyle</styleUrl>
      <Point>
        <coordinates>-122.340141,47.608940</coordinates>
      </Point>
    </Placemark>
    <Placemark id="placemark2">
      <name>Buddha Thai &amp; Bar</name>
      <description>2222 2nd Ave, Seattle, WA</description>
      <styleUrl>#barStyle</styleUrl>
      <Point>
        <coordinates>-122.344391,47.613590</coordinates>
      </Point>
    </Placemark>
    <Placemark id="placemark3">
      <name>The Melting Pot</name>
      <description>14 Mercer St, Seattle, WA</description>
      <styleUrl>#restaurantStyle</styleUrl>
      <Point>
        <coordinates>-122.356445,47.624561</coordinates>
      </Point>
    </Placemark>
    <Placemark id="placemark4">
      <name>Ipanema Grill</name>
      <description>1225 1st Ave, Seattle, WA</description>
      <styleUrl>#restaurantStyle</styleUrl>
      <Point>
        <coordinates>-122.337654,47.606365</coordinates>
      </Point>
    </Placemark>
    <Placemark id="placemark5">
      <name>Sake House</name>
      <description>2230 1st Ave, Seattle, WA</description>
      <styleUrl>#barStyle</styleUrl>
      <Point>
      <coordinates>-122.345673,47.612823</coordinates>
      </Point>
    </Placemark>
    <Placemark id="placemark6">
      <name>Crab Pot</name>
      <description>1301 Alaskan Way, Seattle, WA</description>
      <styleUrl>#restaurantStyle</styleUrl>
      <Point>
        <coordinates>-122.340363,47.605961</coordinates>
      </Point>
    </Placemark>
    <Placemark id="placemark7">
      <name>Mama's Mexican Kitchen</name>
      <description>2234 2nd Ave, Seattle, WA</description>
      <styleUrl>#barStyle</styleUrl>
      <Point>
        <coordinates>-122.345467,47.613976</coordinates>
      </Point>
    </Placemark>
    <Placemark id="placemark8">
      <name>Wingdome</name>
      <description>1416 E Olive Way, Seattle, WA</description>
      <styleUrl>#barStyle</styleUrl>
      <Point>
        <coordinates>-122.326584,47.617214</coordinates>
      </Point>
    </Placemark>
    <Placemark id="placemark9">
      <name>Piroshky Piroshky</name>
      <description>1908 Pike pl, Seattle, WA</description>
      <styleUrl>#restaurantStyle</styleUrl>
      <Point>
        <coordinates>-122.342834,47.610126</coordinates>
      </Point>
    </Placemark>
 </Document>
</kml>

Making a Line

One of the best things about databases is their ability to combine information. For instance, a natural expression of a series of points is a line, or in KML, a <linestring>. This is actually simpler to accomplish than creating a series of points. Create a script that creates the structure of a single Placemark. Place a <linestring> element in the Placemarks. Then query the database for all the coordinates, ordered by the id of the row.
Here's a sample PHP script that creates a <linestring> between all the restaurants, in order of their id, at a 100 meter altitude, with extrusion. While that won't show up on Google Maps, in Google Earth this script creates a 100-meter-tall wall running through all the restaurant locations in Google Earth, in the order they were entered into the database. phpsql_genkml_ls.php:
<?php
require('phpsqlajax_dbinfo.php');

// Opens a connection to a MySQL server
$connection = mysql_connect ($server, $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 GROUP_CONCAT(lng, ',', lat, ',', '100' separator ' ') AS coordinates FROM markers WHERE type = 'restaurant';";

$result = mysql_query($query);
if (!$result) 
{
  die('Invalid query: ' . mysql_error());
}

// Start KML file, create parent node
$dom = new DOMDocument('1.0','UTF-8');

//Create the root KML element and append it to the Document
$node = $dom->createElementNS('http://earth.google.com/kml/2.1','kml');
$parNode = $dom->appendChild($node);

//Create a Folder element and append it to the KML element
$fnode = $dom->createElement('Folder');
$folderNode = $parNode->appendChild($fnode);

//Iterate through the MySQL results
$row = @mysql_fetch_assoc($result);

//Create a Placemark and append it to the document
$node = $dom->createElement('Placemark');
$placeNode = $folderNode->appendChild($node);

//Create an id attribute and assign it the value of id column
$placeNode->setAttribute('id','linestring1');

//Create name, description, and address elements and assign them the values of 
//the name, type, and address columns from the results

$nameNode = $dom->createElement('name','My path');
$placeNode->appendChild($nameNode);
$descNode= $dom->createElement('description', 'This is the path that I took through my favorite restaurants in Seattle');
$placeNode->appendChild($descNode);

//Create a LineString element
$lineNode = $dom->createElement('LineString');
$placeNode->appendChild($lineNode);
$exnode = $dom->createElement('extrude', '1');
$lineNode->appendChild($exnode);
$almodenode =$dom->createElement(altitudeMode,'relativeToGround');
$lineNode->appendChild($almodenode);

//Create a coordinates element and give it the value of the lng and lat columns from the results

$coorNode = $dom->createElement('coordinates',$row['coordinates']);
$lineNode->appendChild($coorNode);
$kmlOutput = $dom->saveXML();

//assign the KML headers. 
header('Content-type: application/vnd.google-earth.kml+xml');
echo $kmlOutput;
?>
The output of that script looks like this. phpsqlkml_expectedoutput_ls.kml:
<?xml version='1.0' encoding='UTF-8'?>
<kml xmlns='http://earth.google.com/kml/2.1'>
  <Folder>
    <Placemark id='linestring1'>
      <name>My path</name>
      <description>This is the path that I took through my favorite restaurants in Seattle</description>
      <LineString>
        <extrude>1</extrude>
        <altitudeMode>relativeToGround</altitudeMode>
        <coordinates>-122.340141,47.608940,100 -122.356445,47.624561,100 
                     -122.337654,47.606365,100 -122.340363,47.605961,100
                     -122.342834,47.610126,100
        </coordinates>
     </LineString>
    </Placemark>
  </Folder>
</kml>

Step 4: Displaying your KML files


Display in Google Earth

You can now easily display this data in Google Earth. The best way to do it is to create a NetworkLink file that points to the script. If you are updating your data frequently, you can set the refresh rate to match how often you update it. Here's an example of a file that would accomplish that. phpmysql_kmlnl.kml:
<?xml version='1.0' encoding='UTF-8'?>
<kml xmlns = 'http://earth.google.com/kml/2.1'>
  <Folder>
    <NetworkLink>
      <Link>
        <href>http://example.com/phpsql_genkml.kml</href>
        <refreshMode>onInterval</refreshMode>
        <refreshInterval>3600</refreshInterval>
      </Link>
    </NetworkLink>
    <NetworkLink>
      <Link>
        <href>http://example.com/phpsql_genkml_ls.kml</href>
        <refreshMode>onInterval</refreshMode>
        <refreshInterval>3600</refreshInterval>
      </Link>
    </NetworkLink>
  </Folder>
</kml>
Change the <href> element to the path to the script on your server. Open up phpmysql_kmlnl.kml with Google Earth. You will see this:
Displaying the NetworkLink in Google Earth

To view the same file in Google Maps, all you need to do is create a map and add the link to the script or to the NetworkLink file. For instance:
function load() 
{
  var map;
  var geoXml;

  if (GBrowserIsCompatible()) 
  {
    map = new GMap2(document.getElementById('map'));
    map.addControl(new GSmallMapControl());
    map.addControl(new GMapTypeControl());
    geoXml = new GGeoXml('http://example.com/phpmysql_kmlnl.kml');
    map.addOverlay(geoXml);
    map.setCenter(new GLatLng(47.613976,-122.345467), 13);
  }
}
Which produces a map like this:
Google Maps Example

Step 5: Where to go from here

So now that you have this database, what do you do with it? Well, the great thing about databases is that you can add to them. The great thing about KML served out of a database is that you can refresh your content. Put those together, and you get a lot of power.
And there's much more you can do in KML. Take advantage of some features unique to Google Earth, such as <NetworkLink> files that use <viewFormat>. This feature allows the <networklink> to send parameters to your script. You can use these parameters to modify what data gets sent back. Or use <TimeStamp> and <TimeSpan> which allow you to do animation of KML Placemarks over a time period. Create more complex table structures to store things like <Polygons> in related tables. Or create a web page that allows other people to enter data into your database, which then gets refreshed the next time the script is called. The possibilities are endless.