Stemming Bahasa Indonesia dengan Algoritma Nazief dan Andriani

Stemming Bahasa Indonesia dengan Algoritma Nazief dan Andriani

Stemming merupakan bagian yang tidak terpisahkan dalam Information Retrieval (IR). Tidak banyak algoritma yang dikhususkan untuk stemming bahasa Indonesia dengan berbagai keterbatasan didalamnya. Algoritma Porter salah satunya, Algoritma ini membutuhkan waktu yang lebih singkat dibandingkan dengan stemming menggunakan Algoritma Nazief & Adriani, namun proses stemming menggunakan Algoritma Porter memiliki prosentase keakuratan (presisi) lebih kecil dibandingkan dengan stemming menggunakan Algoritma Nazief & Adriani. Algoritma Nazief & Adriani sebagai algoritma stemming untuk teks berbahasa Indonesia yang memiliki kemampuan prosentase keakuratan (presisi) lebih baik dari algoritma lainnya. Algoritma ini sangat dibutuhkan dan menentukan dalam proses IR dalam dokumen Indonesia.
Stemming adalah salah satu cara yang digunakan untuk meningkatkan performa IR dengan cara mentransformasi kata-kata dalam sebuah dokumen teks ke bentuk kata dasarnya. Algoritma stemming untuk bahasa yang satu berbeda dengan algoritma stemming untuk bahasa lainnya. Sebagai contoh bahasa Inggris memiliki morfologi yang berbeda dengan bahasa Indonesia sehingga algoritma stemming untuk kedua bahasa tersebut juga berbeda. Proses stemming pada teks berbahasa Indonesia lebih rumit/kompleks karena terdapat variasi imbuhan yang harus dibuang untuk mendapatkan root word(kata dasar) dari sebuah kata.. Pada umumnya kata dasar pada bahasa Indonesia terdiri dari kombinasi:
Prefiks 1 + Prefiks 2 + Kata dasar + Sufiks 3 + Sufiks 2 + Sufiks 1
Sehingga dapat digambarkan menggunakan flowchar sebagai berikut:
Algoritma Nazief & Adriani yang dibuat oleh Bobby Nazief dan Mirna Adriani ini memiliki tahap-tahap sebagai berikut:
  1. Pertama cari kata yang akan diistem dalam kamus kata dasar. Jika ditemukan maka diasumsikan kata adalah root word. Maka algoritma berhenti.
  2. Inflection Suffixes (“-lah”, “-kah”, “-ku”, “-mu”, atau “-nya”) dibuang. Jika berupa particles (“-lah”, “-kah”, “-tah” atau “-pun”) maka langkah ini diulangi lagi untuk menghapus Possesive Pronouns (“-ku”, “-mu”, atau “-nya”), jika ada.
  3. Hapus Derivation Suffixes (“-i”, “-an” atau “-kan”). Jika kata ditemukan di kamus, maka algoritma berhenti. Jika tidak maka ke langkah 3a
    1. Jika “-an” telah dihapus dan huruf terakhir dari kata tersebut adalah “-k”, maka “-k” juga ikut dihapus. Jika kata tersebut ditemukan dalam kamus maka algoritma berhenti. Jika tidak ditemukan maka lakukan langkah 3b.
    2. Akhiran yang dihapus (“-i”, “-an” atau “-kan”) dikembalikan, lanjut ke langkah 4.
  4. Hapus Derivation Prefix. Jika pada langkah 3 ada sufiks yang dihapus maka pergi ke langkah 4a, jika tidak pergi ke langkah 4b.
    1. Periksa tabel kombinasi awalan-akhiran yang tidak diijinkan. Jika ditemukan maka algoritma berhenti, jika tidak
    2. pergi ke langkah 4b.
    3. For i = 1 to 3, tentukan tipe awalan kemudian hapus awalan. Jika root word belum juga ditemukan lakukan langkah 5, jika sudah maka algoritma berhenti. Catatan: jika awalan kedua sama dengan awalan pertama algoritma berhenti.
  5. Melakukan Recoding.
  6. Jika semua langkah telah selesai tetapi tidak juga berhasil maka kata awal diasumsikan sebagai root word. Proses selesai.
Tipe awalan ditentukan melalui langkah-langkah berikut:
  1. Jika awalannya adalah: “di-”, “ke-”, atau “se-” maka tipe awalannya secara berturut-turut adalah “di-”, “ke-”, atau “se-”.
  2. Jika awalannya adalah “te-”, “me-”, “be-”, atau “pe-” maka dibutuhkan sebuah proses tambahan untuk menentukan tipe awalannya.
  3. Jika dua karakter pertama bukan “di-”, “ke-”, “se-”, “te-”, “be-”, “me-”, atau “pe-” maka berhenti.
  4. Jika tipe awalan adalah “none” maka berhenti. Jika tipe awalan adalah bukan “none” maka awalan dapat dilihat pada Tabel 2. Hapus awalan jika ditemukan.
Tabel 1. Kombinasi Awalan Akhiran Yang Tidak Diijinkan
Awalan Akhiran yang tidak diizinkan
be- -i
di- -an
ke- -i, -kan
me- -an
se- -i, -kan
Tabel 2. Cara Menentukan Tipe Awalan Untuk awalan “te-”
Following Characters Tipe Awalan
Set 1 Set 2 Set 3 Set 4
“-r-“ “-r-“ - - none
“-r-“
- - ter-luluh
“-r-“ not (vowel or “-r-”) “-er-“ vowel ter
“-r-“ not (vowel or “-r-”) “-er-“ not vowel ter-
“-r-“ not (vowel or “-r-”) not “-er-“ - ter
not (vowel or “-r-”) “-er-“ vowel - none
not (vowel or “-r-”) “-er-“ not vowel - te
Tabel 3. Jenis Awalan Berdasarkan Tipe Awalannya
Tipe Awalan Awalan yang harus dihapus
di- di-
ke- ke-
se- se-
te- te-
ter- ter-
ter-luluh ter
Untuk mengatasi keterbatasan pada algoritma di atas, maka ditambahkan aturan-aturan dibawah ini:
1. Aturan untuk reduplikasi.
  1. Jika kedua kata yang dihubungkan oleh kata penghubung adalah kata yang sama maka root word adalah bentuk tunggalnya, contoh : “buku-buku” root word-nya adalah “buku”.
  2. Kata lain, misalnya “bolak-balik”, “berbalas-balasan, dan ”seolah-olah”. Untuk mendapatkan root word-nya, kedua kata diartikan secara terpisah. Jika keduanya memiliki root word yang sama maka diubah menjadi bentuk tunggal, contoh: kata “berbalas-balasan”, “berbalas” dan “balasan” memiliki root word yang sama yaitu “balas”, maka root word “berbalas-balasan” adalah “balas”. Sebaliknya, pada kata “bolak-balik”, “bolak” dan “balik” memiliki root word yang berbeda, maka root word-nya adalah “bolak-balik”.
2. Tambahan bentuk awalan dan akhiran serta aturannya.
  1. Untuk tipe awalan “mem-“, kata yang diawali dengan awalan “memp-” memiliki tipe awalan “mem-”.
  1. Tipe awalan “meng-“, kata yang diawali dengan awalan “mengk-” memiliki tipe awalan “meng-”.
Berikut contoh-contoh aturan yang terdapat pada awalan sebagai pembentuk kata dasar.
1. Awalan SE-
Se + semua konsonan dan vokal tetap tidak berubah
Contoh :
  • Se + bungkus   = sebungkus
  • Se + nasib   = senasib
  • Se + arah    = searah
  • Se + ekor    = seekor
2. Awalan ME-
Me + vokal (a,i,u,e,o) menjadi sengau “meng”
Contoh :
  • Me + inap = menginap
  • Me + asuh = mengasuh
  • Me + ubah = mengubah
  • Me + ekor  = mengekor
  • Me + oplos = mengoplos
Me + konsonan b menjadi “mem”
Contoh :
  • Me + beri = member
  • Me + besuk = membesuk
Me + konsonan c menjadi “men”
Contoh :
  • Me + cinta  = mencinta
  • Me + cuci  = mencuci
Me + konsonan d menjadi “men”
Contoh :
  • Me + didik  = mendidik
  • Me + dengkur = mendengkur
Me + konsonan g dan h menjadi “meng”
Contoh :
  • Me + gosok  = menggosok
  • Me + hukum  = menghukum
Me + konsonan j menjadi “men”
Contoh :
  • Me + jepit = menjepit
  • Me + jemput = menjemput
Me + konsonan k menjadi “meng” (luluh)
Contoh :
  • Me + kukus = mengukus
  • Me + kupas  = mengupas
Me + konsonan p menjadi “mem” (luluh)
Contoh :
  • Me + pesona = mempesona
  • Me + pukul = memukul
Me + konsonan s menjadi “meny” (luluh)
Contoh :
  • Me + sapu = menyapu
  • Me + satu = menyatu
Me + konsonan t menjadi “men” (luluh)
Contoh :
  • Me + tanama = menanam
  • Me + tukar  = menukar
Me + konsonan (l,m,n,r,w) menjadi tetap “me”
Contoh :
  • Me + lempar = melempar
  • Me + masak = memasak
  • Me + naik  = menaik
  • Me + rawat = merawat
  • Me + warna = mewarna
3. Awalan KE-
Ke + semua konsonan dan vokal tetap tidak berubah
Contoh :
  • Ke + bawa = kebawa
  • Ke + atas = keatas
4. Awalan PE-
Pe + konsonan (h,g,k) dan vokal menjadi “per”
Contoh :
  • Pe + hitung + an = perhitungan
  • Pe + gelar + an = pergelaran
  • Pe + kantor +   = perkantoran
Pe + konsonan “t” menjadi “pen” (luluh)
Contoh :
  • Pe + tukar  = penukar
  • Pe + tikam = penikam
Pe + konsonan (j,d,c,z) menjadi “pen”
Contoh :
  • Pe + jahit = penjahit
  • Pe + didik = pendidik
  • Pe + cuci = pencuci
  • Pe + zina = penzina
Pe + konsonan (b,f,v) menjadi “pem”
Contoh :
  • Pe + beri = pemberi
  • Pe + bunuh = pembunuh
Pe + konsonan “p” menjadi “pem” (luluh)
Contoh :
  • Pe + pikir  = pemikir
  • Pe + potong  = pemotong
Pe + konsonan “s” menjadi “peny” (luluh)
Contoh :
  • Pe + siram  = penyiram
  • Pe + sabar = penyabar
Pe + konsonan (l,m,n,r,w,y) tetap tidak berubah
Contoh :
  • Pe + lamar = pelamar
  • Pe + makan = pemakan
  • Pe + nanti = penanti
    • Pe + wangi = pewangi
Penerapannya dapat dilihat pada penggalan source code berikut:

require_once(‘Algoritma_stemming.php’);
?>

STEMMING KATA DASAR





if(isset($_POST['katadasar'])){
$teksAsli = $_POST['katadasar'];
//echo $teksAsli;
$length = strlen($teksAsli);
//echo $length;
$pattern = ‘[A-Za-z]‘;
$kata = ”;
if(eregi($pattern,$teksAsli)){
$kata = $teksAsli;
$stemming = NAZIEF($kata);//Memasukkan kata ke fungsi Algoritma Nazief
echo $stemming.’
’;
$kata = ”;
}
}
?>
Untuk algoritma Nazief dan Andriannya sebagai berikut:
require_once(‘koneksi.php’);//Koneksi ke database
// fungsi-fungsi
/*
DP + DP + root word + DS + PP + P
*/
function cekKamus($kata){
// cari di database
$sql = “SELECT * from tb_katadasar where katadasar =’$kata’ LIMIT 1″;
//echo $sql.’
’;
$result = pg_query($sql) or die(pg_error());
if(pg_num_rows($result)==1){
return true; // True jika ada
}else{
return false; // jika tidak ada FALSE
}
}
function Del_Inflection_Suffixes($kata){
$kataAsal = $kata;
if(eregi(‘([km]u|nya|[kl]ah|pun)$’,$kata)){ // Cek Inflection Suffixes
$__kata = eregi_replace(‘([km]u|nya|[kl]ah|pun)$’,”,$kata);
.
.
.
return $__kata;
}
return $kataAsal;
}
// Cek Prefix Disallowed Sufixes (Kombinasi Awalan dan Akhiran yang tidak diizinkan)
function Cek_Prefix_Disallowed_Sufixes($kata){
if(eregi(‘^(be)[[:alpha:]]+(i)$’,$kata)){ // be- dan -i
return true;
}
.
.
.
if(eregi(‘^(se)[[:alpha:]]+(i|kan)$’,$kata)){ // se- dan -i,-kan
return true;
}
return false;
}
// Hapus Derivation Suffixes (“-i”, “-an” atau “-kan”)
function Del_Derivation_Suffixes($kata){
$kataAsal = $kata;
if(eregi(‘(i|an)$’,$kata)){ // Cek Suffixes
$__kata = eregi_replace(‘(i|an)$’,”,$kata);
if(cekKamus($__kata)){ // Cek Kamus
return $__kata;
}
/*– Jika Tidak ditemukan di kamus –*/
.
.
.
}
return $kataAsal;
}
// Hapus Derivation Prefix (“di-”, “ke-”, “se-”, “te-”, “be-”, “me-”, atau “pe-”)
function Del_Derivation_Prefix($kata){
$kataAsal = $kata;
/* —— Tentukan Tipe Awalan ————*/
if(eregi(‘^(di|[ks]e)’,$kata)){ // Jika di-,ke-,se-
$__kata = eregi_replace(‘^(di|[ks]e)’,”,$kata);
if(cekKamus($__kata)){
return $__kata; // Jika ada balik
}
$__kata__ = Del_Derivation_Suffixes($__kata);
if(cekKamus($__kata__)){
return $__kata__;
}
/*————end “diper-”, ———————————————*/
if(eregi(‘^(diper)’,$kata)){
$__kata = eregi_replace(‘^(diper)’,”,$kata);
if(cekKamus($__kata)){
return $__kata; // Jika ada balik
}
.
.
.
}
/*————end “diper-”, ———————————————*/
}
if(eregi(‘^([tmbp]e)’,$kata)){ //Jika awalannya adalah “te-”, “me-”, “be-”, atau “pe-”
.
.
.
.
}
/* — Cek Ada Tidaknya Prefik/Awalan (“di-”, “ke-”, “se-”, “te-”, “be-”, “me-”, atau “pe-”) ——*/
if(eregi(‘^(di|[kstbmp]e)’,$kata) == FALSE){
return $kataAsal;
}
return $kataAsal;
}
function NAZIEF($kata){
$kataAsal = $kata;
/* 1. Cek Kata di Kamus jika Ada SELESAI */
if(cekKamus($kata)){ // Cek Kamus
return $kata; // Jika Ada kembalikan
}
/* 2. Buang Infection suffixes (\-lah”, \-kah”, \-ku”, \-mu”, atau \-nya”) */
$kata = Del_Inflection_Suffixes($kata);
/* 3. Buang Derivation suffix (\-i” or \-an”) */
$kata = Del_Derivation_Suffixes($kata);
/* 4. Buang Derivation prefix */
$kata = Del_Derivation_Prefix($kata);
return $kata;
}
?>
Pada proses stemming menggunakan Algoritma Nazief & Adriani, kamus yang digunakan sangat mempengaruhi hasil stemming. Semakin lengkap kamus yang digunakan maka semakin akurat pula hasil stemming.
Sumber: Agusta, L.2009. Perbandingan Algoritma Stemming Porter Dengan Algoritma Nazief dan Adriani Untuk Stemming Dokumen Teks Bahasa Indonesia. Konferensi Nasional Sistem dan Informatika 2009. . Diakses 10 Juli 2010.

Membuat Aplikasi Android

Membuat Aplikasi Android
Android sebagai “pemain” baru dalam dunia smartphone kini sudah berkembang demikian cepat. Hingga saat ini sudah memasuki versi Android 2.3. Hal ini tidak terlepas dari peran geeks yang memanfaatkan OS ini untuk dikembangkan lebih lanjut karena sifatnya yang open source. Jika pada artikel sebelumnya kita telah membahas bagaimana instalasi Android emulator pada desktop, serta instalasi aplikasi yang sudah ada untuk Android, sekarang kita akan mencoba membuat sebuah aplikasi Map sederhana menggunakan Android emulator.

Aplikasi Map sederhana ini akan kita sambungkan dengan Google Map, jadi jangan lupa koneksi internet ya..

1. Pembuatan Project Baru

Mari kita mulai dengan membuat project baru ketentuan sebagai berikut,
  1. Klik File > New lalu pilih Android Project
  2. Klik Next lalu isikan field-field yang tersedia dengan ketentua sebagai beriktu
  • Project Name : Nama Project yang akan kita buat.
Project Name : My First Map
  • Built Target : Target aplikasi yang akan digunakan untuk menjalankan aplikasi.
Built Target : Kita pilih Google APIs dengan Platform 1.6
  • Application Name : Nama aplikasi yang akan dibuat.
Application Name : My First Map
  • Package Name : Nama paket yang mengacu pada standar penamaan aplikasi java.
Package Name : biz.multimediacenter.myfirstmap
  • Create Activity : Nama aktiviti.
Create Activity : MyFirstMap
  • Min SDK Version : Versi dari Android SDK yang digunakan.
Min SDK Version : 4

2. Pembuatan AVD

  1. Klik Window > Android SDK and AVD Manager
  2. Klik New
  3. Isikan field-field yang tersedia dengan ketentuan sebagai berikut,
  • Name : Nama AVD
Name : AVDapi
  • Target : Target untuk menjalankan aplikasi
Target : Google APIs(Google Inc.)-API Level 4
  • SD Card Size : Kapasitas memori yang akan digunakan
SD Card Size : 100 MB
  • Skin : Jenis layar
Skin : Default (HVGA)
  • Hardware : Perangkat keras yang dibutuhkan
Hardware : Abstracted LCD density

3. Key API

  1. Cari lokasi folder key-nya, biasanya terletak pada C:\Document and Settings\\.android\debug.keystore
  2. Copy file debug.keystore ke sebuah lokasi yang mudah dijangkau, misalkan di folder data di drive D.
  3. Cara membuka debug.keystore dapat melalui DOS dengan melalui Start > Run > CMD
  4. Kemudian cari dimana kita menempatkan JDK\bin kita, misal pada C:\Program Files\jdk 1.6.0_16\bin
  5. Setelah berada pada lokasi yang benar maka perintah yang kita gunakan adalah : keytool –list –alias androiddebugkey –keystore D:\data\debug.keystore –storepass android –keypass android
  6. Setelah itu masuk ke masuk ke alamat http://code.google.com/android/add-ons/google-apis/maps-api-signup.html untuk mendaftarkan key Certificate fingerprint kita.
  7. Masukkan key Certificate fingerprint pada My Certicate’s MD5 fingerprint :
  8. Setelah itu kita akan mendapatkan API Key Google Map

4. Koneksi Google Map

Dalam pembuatan aplikasi peta sederhana ini, kita menggunakan fasilitas Google Map yang dikembangkan oleh Google Inc. Jadi untuk dapat menggunakannya maka di dalam pembuatannya kita sisipkan perintah yang akan menghubungkan aplikasi kita dengan Google Map. Dalam hal ini kita tambahkan
  1. com.google.android.maps.MapViewandroid:id”@+id/map”
  2. android:apikey=””
sehingga pada file main.xml akan menjadi seperti di bawah ini,



android:layout_width=”fill_parent”
android:layout_height=”fill_parent”>
<com.google.android.maps.MapView android:id=”@+id/map”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:apiKey=”0N7Hy8N-J4GRSHu6EBqBPNNmCZIGnxFWaJyCLAQ”
android:clickable=”true” />


android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_alignParentBottom=”true”
android:layout_alignParentLeft=”true” >

Sedangkan untuk koneksi dengan internet, kita haru menambahkan permission dan library pada file AndroidManifest.xml, yaitu:
  1. Permission INTERNET dan ACCESS_COARSE_LOCATION
  2. Pada elemen , tambahkan elemen dengan android:name= ”com.google.android.maps”, sebagai tanda untuk menggunakan Android API
Sehingga file AndroidManifest.xml secara menjadi seperti ini:



package=”biz.multimediacenter.myfirstmap”
android:versionCode=”1″
android:versionName=”1.0″>






android:label=”@string/app_name”>










5. Fasilitas Zoom

Fasilitas zoom sangat diperlukan pada aplikasi peta digital untuk mengetahui lebih detail tempat yang ingin dilihat. Di dalam Android, kita bisa mengontrol secara langsung level zoom melalui method setzoom() pada getMapController(). Nilai ini menggunakan angka integer, diamana 1 (satu) akan memperlihatkan peta dunia secara keseluruhan, dan 21 (dua puluh satu) adalah level terdekat yang bisa kita dapatkan.
Setiap  level merupakan kelipatan dari efektif resolusi layer, level 1 (satu) sama dengan 256 pixel, sedangkan level 21 (dua puluh satu) sama dengan 268,435,456 pixel. Layar handphone tentu tidak sebesar itu, sehingga menggunakan level 16 (enam belas) untuk melihat peta seukuran beberapa blok pada sebuah lokasi.
Untuk membuat aplikasi memiliki zoom level, kita membutuhkan beberapa hal:
  1. Kita menentukan tempat untuk menempatkan kontrol zoom, dan kita bisa mengesetnya hanya terhlihat ketika kita membutuhkan. Misal kita tempatkan overlay di atas peta, pada pojok kiri bawah layar. Kita menggunakan LinearLayout atau kontainer sederhana untuk kontol zoom layout kita.
  2. Pada Activity method onCreate(), kita bisa mendapatkan kontrol zoom kontainer melalui findViewById().
  3. Tambahkan hasil dari map.getZoomControl() pada kontainer.
Sebagai contoh, ini baris kode dari method onCreate(), yang dimaksud sebelumnya:

ViewGroup zom=(ViewGroup) findViewById (R.id.zoom);
Zoom.addView(map.getZoomControl());

Kemudian kita dapat memanggil kontrol zoom agar terlihat dengan memanggil displayZoomControl() pada mapView kita, atau bisa juga secara otomatis terlhiat ketika penggunanya menyentuh layar.
Biasanya kita akan butuh untuk mengontrol peta, selain level zoom, misal lokasi pengguna pada aplikasi semacam where I am, atau lokasi-lokasi tertentu yang kita inginkan, ini akan memerlukan GeoPoint sebagai parameter lokasi tersebut. GeoPoint sebagai parameter lokasi tersebut. GeoPoint merupakan titik alamat dari lokasi, yaitu Latitude dan Longtitude, yang direpresentasikan ke dala deretan angka integer. Dan untuk mengubah posisi map kita bisa memanggil setCenter() pada mapController.

6. GeoPoint

Untuk mendapatkan GeoPoint salah satunya bisa melihat pada Google Maps. Misalkan kita menujut ke Indonesia. Dan disini kita akan mengambil GeoPoint untuk kota Depok dengan titik Universitas Gunadarma. Klik kanan, lalu pilih What’s here?
Sehingga pada jendela sebelah kiri akan muncul angka GeoPoint dari titik tersebut, atau pada field searching. Untuk Universitas Gunadarma kita mendapatkan GeoPoint dengan deretan angka integer, -6.36806,106.833029

7. Rugged Terrain

Seperti juga Google Maps pada komputer yang bisa memperlihatkan image peta terrain dari satellite, Android map juga bisa melakukan hal seperti itu.
Dengan menggunakan method toggleSatellite() pada MapView, kita bisa melihat peta perspektif dari satellite yaitu terrain. Kita bisa membuat triggernya dari menu ataupun dari keypad. Contoh penggunaan keypad yaitu dengan mengeset untuk berpindah mode peta terrain dari satellite pada keypad S, dan untuk menampilkan zoom kontrol pada keypad
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_S) {
map.setSatellite(!map.isSatellite());
return(true);
}
else if (keyCode == KeyEvent.KEYCODE_Z) {
map.displayZoomControls(true);
return(true);
}

8. Push Pin

Ketika kita menggunakan Google Maps, kita mungkin pernah menggunakan atau melihat sesuatu di atas peta, seperti “push-pins” yang menandakan suatu tempat. Dimana sebenarnya push pin tersebut terpisah dari peta, dia memiliki layer sendiri, diatas layer peta. Android map juga menyediakan fasilitas layering inim sehingga kita bisa menandai peta dengan push pin sesuai yang diinginkan.
Setiap overlay yang ingin kita tambahkan pada peta, harus diimplementasikan sebagai subkelas dari Ovelay. Terdapat sebuah subkelas ItemizedOverlay ketika kita ingin melihat semacam push pin atau sejenisnya dan ItemizedOverlay memudahkan proses itu.
Untuk menetapkan kelas overlay pada peta, kita bisa memanggil getOverlays() pada MapView kita, dan gunakan add() sebagai instance dari Overlay:
marker.setBounds(0,0, marker.getIntrinsicWidth(),marker.getIntrinsicHeight());
map.getOverlays().add(new SitesOverlay(marker));

9. Touch Screen

Subkelas Overlay juga mengimplementasikan method onTap(), yang akan menangani sentuhan pada layar seperti pada Google Maps, mengklik pada push pin akan mentriger sebuah balon pop up informasi mengenai lokasi. Dengan onTap(), kita dapat melakukan hal yang sama pada Android.
@Override
protected boolean onTap(int i) {
Toast.makeText(MyFirstMap.this,
items.get(i).getSnippet(),
Toast.LENGTH_SHORT).show();
return(true);
}
Android memiliki built-in overlay untuk menghandle dua skenario keadaan:
  1. Menunjukkan dimana kita pada peta, berdasarkan GPS atau lokasi lain yang disediakan
  2. Menunjukkan titik dimana kita ditetapkan, berdasarkan pada built-in sensor kompas apabila tersedia.
Yang harus kita lakukan adalah membuat instance dari MyLocationOverlay(), tambahkan pada daftar MapViews dari overlay, dan mengeset pada enable atau disable fitur ini pada waktu yang ditentukan. Dinama waktu ini didasarkan pada umur penggunaan batttery, tidak perlu meng-update lokasi atau arah ketika activity di pause, untuk itu direkomendasikan kita meng-enable fitur ini dengan onResume() dan disable dengan onPause().
Disini kita memberikan penanda (marker) pada titik-titik GeoPoint yang kita masukkan koordinatnya ke dalam peta kita. Yaitu dengan membuat objek gambar kecil, dengan menggunakan formatpng, dan kita manamakannya marker.png. untuk membuatnya bisa menggunakan pengolah gambar yang kita kuasai, dengan ukuran 22×23 pixel kemudian copy ke folder res/drawable-mdpi/marker.png

10. Tampilan

  • Tampilan Satelit

  • Tampilan Peta


Sumber : http://cingciripit.com/2011/01/membuat-aplikasi-android-3/

Membuat Aplikasi Google Map Kita Sendiri di Android

Membuat Aplikasi Google Map Kita Sendiri di Android
Sebenarnya tutorial ini sudah ada di situs android sendiri, namun saya ingin menerjemahkan untuk yang kurang mengerti akan hal ini. Jika kita sudah mendownload eclipse dan android sdk, kita bisa memulai untuk mencoba membuat aplikasi ini :)
Pertama, buka Eclipse kita.
Eclipse Galileo
Eclipse Galileo
Selanjutnya kita buat sebuah Project baru dengan menekan menu File->New->Android Project.
Android Project
Android Project
Setelah itu kita masukkan nama project : GoogleMapKu, Di sini saya menyimpan pada D:/Project. Centang Google Api v7, karena saya di sini menggunakan Eclair, karena tidak memiliki sdk yang lebih baru. :P Sesuaikan dengan gambar di bawah ini.
New Android Project
New Android Project
Maka tampilan di package explorer akan jadi seperti ini.
Package Explorer
Package Explorer
Jika kita buka folder-folder yang ada di dalam project tersebut, maka kita dapat menemukan banyak fungsi, diantaranya :
  • src, digunakan untuk source code aplikasi kita.
  • gen, merupakan folder berisi class yang di-generate langsung oleh eclipse, tidak perlu kita sentuh. R.java merupakan sebuah pointer untuk resource gambar atau file lain pada project eclipse.
  • assets, folder yang satu ini saya tidak pernah menggunakan, mungkin ada yang pernah menggunakannya ? X)
  • res, merupakan folder sumber segala sesuatu yang berhubungan dengan file yang ditampilkan pada interface aplikasi.
  • AndroidManifest.xml, digunakan sebagai deklarasi aplikasi kita, berisi permission untuk mengakses seperti sms, internet, gps, dan lainnya.
Tree View
Tree View
Sekarang kita tes aplikasi kita, namun sebelum itu kita perlu membuat emulatornya terlebih dahulu. Tekan menu Window -> Andoroid SDK and AVD Manager, maka akan muncul dialog seperti berikut :
Android SDK and ADV Manager
Android SDK and ADV Manager
Jika kita belum membuat sebuah emulator, maka kita buat terlebih dahulu dengan mengklik tombok new. Isikan seperti gambar di bawah ini. Lalu tekan Create AVD.
Emulator
Emulator
Setelah itu lakukan start emulator. Pastikan centang launch from snapshot, hal ini agar ketika kita meng-close emulator, saat kita nyalakan kembali, tidak perlu me-reboot dari awal lagi.
Launch Emulator
Launch Emulator
Proses ini agak menunggu lama, jika sudah sampai ke screen utama emulator, jalankan aplikasi kita dengan menekan tombol Run, kemudian pilih Android Application.
Run As
Run As
Jika berhasil, kita dapati hasil seperti berikut ini :
Hasil Emulator
Hasil Emulator
Nah, jika sampai di sini kita berhasil, maka kita berhasil. :D Sekarang kita mulai melakukan coding terhadap google mapnya. Karena google map api membutuhkan key, terlebih dahulu kita generate key yang kita punyai. Di sini saya menggunakan Windows 7 dan username saya ifebfeb, jadi lokasi debug.keystore berada pada :
C:\Users\ifebfeb\.android\debug.keystore
buka terminal / cmd.exe, change directory dengan mengetikkan cd “Program Files\Java\jdk1.6.0_21\bin”, setelah itu ketikkan : keytool -list -alias androiddebugkey -keystore C:\Users\ifebfeb\.android\debug.keystore -storepass android -keypass android. Untuk lebih jelasnya lihat pada gambar :
Terminal
Terminal
Setelah kita generate key kita buka web di sini, maka kita copy-kan ke textbox yang ada. Jangan lupa untuk mencentang checkbox “I have read and agree with the terms and conditions
Oke, jika sudah kita dapatkan API key kita sendiri, sekarang saatnya menuju ke pemrograman. Buka file main.xml pada folder /res/layout. Isikan dengan xml berikut, jangan lupa menyertakan API key-nya. API key tidak boleh sama antara saya dengan Anda, jadi harus benar-benar meng-generate API key-nya. :)
1xml version="1.0" encoding="utf-8"?>
2<com.google.android.maps.MapView
4    android:id="@+id/mapview"
5    android:layout_width="fill_parent"
6    android:layout_height="fill_parent"
7    android:clickable="true"
8    android:apiKey="0UoFJyNCg8Upozd2cspAO3ks-rd_ziS5azfpYbA"
9/>
Jika sudah, sekarang kita buka MainActivity.java yang berada pada folder /src/com.iddev.googlemap, Ganti menjadi seperti ini :
01package com.iddev.googlemap;
02
03import com.google.android.maps.GeoPoint;
04import com.google.android.maps.MapActivity;
05import com.google.android.maps.MapController;
06import com.google.android.maps.MapView;
07
08import android.os.Bundle;
09import android.view.Window;
10
11public class MainActivity extends MapActivity {
12    public MapView mapView;
13
14    /** Called when the activity is first created. */
15    @Override
16    public void onCreate(Bundle savedInstanceState) {
17        super.onCreate(savedInstanceState);
18
19        requestWindowFeature(Window.FEATURE_NO_TITLE);
20        setContentView(R.layout.main);
21
22        mapView = (MapView) findViewById(R.id.mapview);
23        mapView.setBuiltInZoomControls(true);
24
25        // set posisi tengah dari map
26        MapController mapController = mapView.getController();
27        mapController.setCenter(new GeoPoint(-7298115, 112739451));
28        mapController.setZoom(12);
29    }
30
31    @Override
32    protected boolean isRouteDisplayed() {
33        return false;
34    }
35}
Kemudian ubah file AndroidManifest.xml menjadi seperti ini :
01xml version="1.0" encoding="utf-8"?>
02<manifest xmlns:android="http://schemas.android.com/apk/res/android"
03      package="com.iddev.googlemap"
04      android:versionCode="1"
05      android:versionName="1.0">
06     
07
08    <application android:icon="@drawable/icon" android:label="@string/app_name">
09        <activity android:name=".MainActivity"
10                  android:label="@string/app_name"
11                  android:theme="@android:style/Theme.NoTitleBar">
12            <intent-filter>
13                <action android:name="android.intent.action.MAIN" />
14                <category android:name="android.intent.category.LAUNCHER" />
15            intent-filter>
16        activity>
17        <uses-library android:name="com.google.android.maps" />
18    application>
19    <uses-permission android:name="android.permission.INTERNET" />
20manifest>
Sekarang Jalankan aplikasi, dan.. Voila!! Aplikasi Google Map buatan kita sudah jadi. Nantikan Part Selanjutnya ;)
Hasil Akhir
Hasil Akhir
Referensi Asli : http://developer.android.com/resources/tutorials/views/hello-mapview.html

Using Google Maps in Android

Using Google Maps in Android
Google Maps is one of the many applications bundled with the Android platform. In addition to simply using the Maps application, you can also embed it into your own applications and make it do some very cool things. In this article, I will show you how to use Google Maps in your Android applications and how to programmatically perform the following:
  1. Change the views of Google Maps
  2. Obtain the latitude and longitude of locations in Google Maps
  3. Perform geocoding and reverse geocoding
  4. Add markers to Google Maps

Creating the Project

Using Eclipse, create a new Android project and name GoogleMaps as shown in Figure 1.

Figure 1 Creating a new Android project using Eclipse

Obtaining a Maps API key

Beginning with the Android SDK release v1.0, you need to apply for a free Google Maps API key before you can integrate Google Maps into your Android application. To apply for a key, you need to follow the series of steps outlined below. You can also refer to Google's detailed documentation on the process at http://code.google.com/android/toolbox/apis/mapkey.html.
First, if you are testing the application on the Android emulator, locate the SDK debug certificate located in the default folder of "C:\Documents and Settings\\Local Settings\Application Data\Android". The filename of the debug keystore is debug.keystore. For deploying to a real Android device, substitute the debug.keystore file with your own keystore file. In a future article I will discuss how you can generate your own keystore file.
For simplicity, copy this file (debug.keystore) to a folder in C:\ (for example, create a folder called "C:\Android").
Using the debug keystore, you need to extract its MD5 fingerprint using the Keytool.exe application included with your JDK installation. This fingerprint is needed to apply for the free Google Maps key. You can usually find the Keytool.exe from the "C:\Program Files\Java\\bin" folder.
Issue the following command (see also Figure 2) to extract the MD5 fingerprint.
keytool.exe -list -alias androiddebugkey -keystore "C:\android\debug.keystore" -storepass android -keypass android
Copy the MD5 certificate fingerprint and navigate your web browser to: http://code.google.com/android/maps-api-signup.html. Follow the instructions on the page to complete the application and obtain the Google Maps key.

Figure 2 Obtaining the MD5 fingerprint of the debug keystore
To use the Google Maps in your Android application, you need to modify your AndroidManifest.xml file by adding the element together with the INTERNET permission:
 version="1.0" encoding="utf-8"?>
 xmlns:android="http://schemas.android.com/apk/res/android"
      package="net.learn2develop.GoogleMaps"
      android:versionCode="1"
      android:versionName="1.0.0">
     android:icon="@drawable/icon" android:label="@string/app_name">
 
     android:name="com.google.android.maps" />  
 
         android:name=".MapsActivity"
                  android:label="@string/app_name">
            >
                 android:name="android.intent.action.MAIN" />
                 android:name="android.intent.category.LAUNCHER" />
            >
        >
    >
 
     android:name="android.permission.INTERNET" />
 
>
>

Displaying the Map

To display the Google Maps in your Android application, modify the main.xml file located in the res/layout folder. You shall use the element to display the Google Maps in your activity. In addition, let's use the element to position the map within the activity:
 version="1.0" encoding="utf-8"?>
 xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent">
 
    .google.android.maps.MapView 
        android:id="@+id/mapView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:enabled="true"
        android:clickable="true"
        android:apiKey="0l4sCTTyRmXTNo7k8DREHvEaLar2UmHGwnhZVHQ"
        />
 
>
Notice from above that I have used the Google Maps key that I obtained earlier and put it into the apiKey attribute.
In the MapsActivity.java file, modify the class to extend from the MapActivity class, instead of the normal Activity class:
package net.learn2develop.GoogleMaps;
 
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import android.os.Bundle;
 
public class MapsActivity extends MapActivity 
{    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
 
    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }
}
Observe that if your class extends the MapActivity class, you need to override the isRouteDisplayed() method. You can simply do so by setting the method to return false.
That's it! That's all you need to do to display the Google Maps in your application. Press F11 in Eclipse to deploy the application onto an Android emulator. Figure 3 shows the Google map in all its glory.

Figure 3 Google Maps in your application
At this juncture, take note of a few troubleshooting details. If your program does not run (i.e. it crashes), then it is likely you forgot to put the following statement in your AndroidManifest.xml file:
     android:name="com.google.android.maps" />
If your application manages to load but you cannot see the map (all you see is a grid), then it is very likely you do not have a valid Map key, or that you did not specify the INTERNET permission:
     android:name="android.permission.INTERNET" />

Displaying the Zoom View

The previous section showed how you can display the Google Maps in your Android device. You can drag the map to any desired location and it will be updated on the fly. However, observe that there is no way to zoom in or out from a particular location. Thus, in this section, you will learn how you can let users zoom into or out of the map.
First, add a element to the main.xml file as shown below:
 version="1.0" encoding="utf-8"?>
 xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent">
 
    .google.android.maps.MapView 
        android:id="@+id/mapView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:enabled="true"
        android:clickable="true"
        android:apiKey="0l4sCTTyRmXTNo7k8DREHvEaLar2UmHGwnhZVHQ"
        />
 
     android:id="@+id/zoom" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_alignParentBottom="true" 
        android:layout_centerHorizontal="true" 
        /> 
 
>
You will use the element to hold the two zoom controls in Google Maps (you will see this shortly).
In the MapsActivity.java file, add the following imports:
import com.google.android.maps.MapView.LayoutParams;  
import android.view.View;
import android.widget.LinearLayout;
and add the following code after the line setContentView(R.layout.main);
        mapView = (MapView) findViewById(R.id.mapView);
        LinearLayout zoomLayout = (LinearLayout)findViewById(R.id.zoom);  
        View zoomView = mapView.getZoomControls(); 
 
        zoomLayout.addView(zoomView, 
            new LinearLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, 
                LayoutParams.WRAP_CONTENT)); 
        mapView.displayZoomControls(true);
The complete MapsActivity.java file is given below:
package net.learn2develop.GoogleMaps;
 
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.MapView.LayoutParams;  
 
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
 
public class MapsActivity extends MapActivity 
{    
    MapView mapView; 
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
 
 
        mapView = (MapView) findViewById(R.id.mapView);
        LinearLayout zoomLayout = (LinearLayout)findViewById(R.id.zoom);  
        View zoomView = mapView.getZoomControls(); 
 
        zoomLayout.addView(zoomView, 
            new LinearLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, 
                LayoutParams.WRAP_CONTENT)); 
        mapView.displayZoomControls(true);
 
    }
 
    @Override
    protected boolean isRouteDisplayed() {
        // TODO Auto-generated method stub
        return false;
    }
}
Basically, you obtain the MapView instance on the activity, obtain its zoom controls and then add it to the LinearLayout element you added to the activity earlier on. In the above case, the zoom control will be displayed at the bottom of the screen. When you now press F11 in Eclipse, you will see the zoom controls when you touch the map (see Figure 4).

Figure 4 Using the zoom controls in Google Maps
Using the zoom control, you can zoom in or out of a location by simply touching the "+ or "-" buttons on the screen.
Alternatively, you can also programmatically zoom in or out of the map using the zoomIn() and zoomOut() methods from the MapController class:
package net.learn2develop.GoogleMaps;
 
//...
import android.os.Bundle;
import android.view.KeyEvent;
 
public class MapsActivity extends MapActivity 
{    
    MapView mapView; 
 
    public boolean onKeyDown(int keyCode, KeyEvent event) 
    {
        MapController mc = mapView.getController(); 
        switch (keyCode) 
        {
            case KeyEvent.KEYCODE_3:
                mc.zoomIn();
                break;
            case KeyEvent.KEYCODE_1:
                mc.zoomOut();
                break;
        }
        return super.onKeyDown(keyCode, event);
    }    
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        //...
    }
 
    @Override
    protected boolean isRouteDisplayed() {
        // TODO Auto-generated method stub
        return false;
    }
}
In the above code, when the user presses the number 3 on the keyboard the map will zoom in into the next level. Pressing number 1 will zoom out one level.

Changing Views of the Map

By default, the Google Maps displays in the map mode. If you wish to display the map in satellite view, you can use the setSatellite() method of the MapView class, like this:
        mapView.setSatellite(true);
You can also display the map in street view, using the setStreetView() method:
        mapView.setStreetView(true);
Figure 5 shows the Google Maps displayed in satellite and street views, respectively.

Figure 5 Displaying Google Maps in satellite and street views

Displaying a Particular Location

Be default, the Google Maps displays the map of the United States when it is first loaded. However, you can also set the Google Maps to display a particular location. In this case, you can use the animateTo() method of the MapController class.
The following code shows how this is done:
package net.learn2develop.GoogleMaps;
 
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MapView.LayoutParams;
 
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
 
public class MapsActivity extends MapActivity 
{    
    MapView mapView; 
    MapController mc;
    GeoPoint p;
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
 
        mapView = (MapView) findViewById(R.id.mapView);
        LinearLayout zoomLayout = (LinearLayout)findViewById(R.id.zoom);  
        View zoomView = mapView.getZoomControls(); 
 
        zoomLayout.addView(zoomView, 
            new LinearLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, 
                LayoutParams.WRAP_CONTENT)); 
        mapView.displayZoomControls(true);
 
        mc = mapView.getController();
        String coordinates[] = {"1.352566007", "103.78921587"};
        double lat = Double.parseDouble(coordinates[0]);
        double lng = Double.parseDouble(coordinates[1]);
 
        p = new GeoPoint(
            (int) (lat * 1E6), 
            (int) (lng * 1E6));
 
        mc.animateTo(p);
        mc.setZoom(17); 
        mapView.invalidate();
    }
 
    @Override
    protected boolean isRouteDisplayed() {
        // TODO Auto-generated method stub
        return false;
    }
}
In the above code, you first obtain a controller from the MapView instance and assign it to a MapController object (mc). You use a GeoPoint object to represent a geographical location. Note that for this class the latitude and longitude of a location are represented in micro degrees. This means that they are stored as integer values. For a latitude value of 40.747778, you need to multiply it by 1e6 to obtain 40747778.
To navigate the map to a particular location, you can use the animateTo() method of the MapController class (an instance which is obtained from the MapView object). The setZoom() method allows you to specify the zoom level in which the map is displayed. Figure 6 shows the Google Maps displaying the map of Singapore.

Figure 6 Navigating to a particular location on the map

Adding Markers

Very often, you may wish to add markers to the map to indicate places of interests. Let's see how you can do this in Android. First, create a GIF image containing a pushpin (see Figure 7) and copy it into the res/drawable folder of the project. For best effect, you should make the background of the image transparent so that it does not block off parts of the map when the image is added to the map.

Figure 7 Adding an image to the res/drawable folder
To add a marker to the map, you first need to define a class that extends the Overlay class:
package net.learn2develop.GoogleMaps;
 
import java.util.List;
 
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.MapView.LayoutParams;
 
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
 
public class MapsActivity extends MapActivity 
{    
    MapView mapView; 
    MapController mc;
    GeoPoint p;
 
    class MapOverlay extends com.google.android.maps.Overlay
    {
        @Override
        public boolean draw(Canvas canvas, MapView mapView, 
        boolean shadow, long when) 
        {
            super.draw(canvas, mapView, shadow);                   
 
            //---translate the GeoPoint to screen pixels---
            Point screenPts = new Point();
            mapView.getProjection().toPixels(p, screenPts);
 
            //---add the marker---
            Bitmap bmp = BitmapFactory.decodeResource(
                getResources(), R.drawable.pushpin);            
            canvas.drawBitmap(bmp, screenPts.x, screenPts.y-50, null);         
            return true;
        }
    } 
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        //...
    }
 
    @Override
    protected boolean isRouteDisplayed() {
        // TODO Auto-generated method stub
        return false;
    }
}
In the MapOverlay class that you have defined, override the draw() method so that you can draw the pushpin image on the map. In particular, note that you need to translate the geographical location (represented by a GeoPoint object, p) into screen coordinates.
As you want the pointed tip of the push pin to indicate the position of the location, you would need to deduct the height of the image (which is 50 pixels) from the y-coordinate of the point (see Figure 8) and draw the image at that location.

Figure 8 Adding an image to the map
To add the marker, create an instance of the MapOverlap class and add it to the list of overlays available on the MapView object:
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
 
        //...
 
        mc.animateTo(p);
        mc.setZoom(17); 
 
        //---Add a location marker---
        MapOverlay mapOverlay = new MapOverlay();
        List<Overlay> listOfOverlays = mapView.getOverlays();
        listOfOverlays.clear();
        listOfOverlays.add(mapOverlay);        
 
        mapView.invalidate();
    }
Figure 9 shows how the pushpin looks like when added to the map.

Figure 9 Adding a marker to the map

Getting the Location that was touched

After using Google Maps for a while, you may wish to know the latitude and longitude of a location corresponding to the position on the screen that you have just touched. Knowing this information is very useful as you can find out the address of a location, a process known as Geocoding (you will see how this is done in the next section).
If you have added an overlay to the map, you can override the onTouchEvent() method within the Overlay class. This method is fired every time the user touches the map. This method has two parameters - MotionEvent and MapView. Using the MotionEvent parameter, you can know if the user has lifted his finger from the screen using the getAction() method. In the following code, if the user has touched and then lifted his finger, you will display the latitude and longitude of the location touched:
    class MapOverlay extends com.google.android.maps.Overlay
    {
        @Override
        public boolean draw(Canvas canvas, MapView mapView, 
        boolean shadow, long when) 
        {
           //...
        }
 
        @Override
        public boolean onTouchEvent(MotionEvent event, MapView mapView) 
        {   
            //---when user lifts his finger---
            if (event.getAction() == 1) {                
                GeoPoint p = mapView.getProjection().fromPixels(
                    (int) event.getX(),
                    (int) event.getY());
                    Toast.makeText(getBaseContext(), 
                        p.getLatitudeE6() / 1E6 + "," + 
                        p.getLongitudeE6() /1E6 , 
                        Toast.LENGTH_SHORT).show();
            }                            
            return false;
        }        
    }
Figure 10 shows this in action.

Figure 10 Displaying the latitude and longitude of a point touched on the map

Geocoding and Reverse Geocoding

If you know the latitude and longitude of a location, you can find out its address using a process known as Geocoding. Google Maps in Android supports this via the Geocoder class. The following code shows how you can find out the address of a location you have just touched using the getFromLocation() method:
    class MapOverlay extends com.google.android.maps.Overlay
    {
        @Override
        public boolean draw(Canvas canvas, MapView mapView, 
        boolean shadow, long when) 
        {
          //...
        }
 
        @Override
        public boolean onTouchEvent(MotionEvent event, MapView mapView) 
        {   
            //---when user lifts his finger---
            if (event.getAction() == 1) {                
                GeoPoint p = mapView.getProjection().fromPixels(
                    (int) event.getX(),
                    (int) event.getY());
 
                Geocoder geoCoder = new Geocoder(
                    getBaseContext(), Locale.getDefault());
                try {
                    List<Address> addresses = geoCoder.getFromLocation(
                        p.getLatitudeE6()  / 1E6, 
                        p.getLongitudeE6() / 1E6, 1);
 
                    String add = "";
                    if (addresses.size() > 0) 
                    {
                        for (int i=0; i<addresses.get(0).getMaxAddressLineIndex(); 
                             i++)
                           add += addresses.get(0).getAddressLine(i) + "\n";
                    }
 
                    Toast.makeText(getBaseContext(), add, Toast.LENGTH_SHORT).show();
                }
                catch (IOException e) {                
                    e.printStackTrace();
                }   
                return true;
            }
            else                
                return false;
        }        
    }
Figure 11 shows the above code in action.

Figure 11 Performing Geocoding in Google Maps
If you know the address of a location but want to know its latitude and longitude, you can do so via reverse-Geocoding. Again, you can use the Geocoder class for this purpose. The following code shows how you can find the exact location of the Empire State Building by using the getFromLocationName() method:
        Geocoder geoCoder = new Geocoder(this, Locale.getDefault());    
        try {
            List<Address> addresses = geoCoder.getFromLocationName(
                "empire state building", 5);
            String add = "";
            if (addresses.size() > 0) {
                p = new GeoPoint(
                        (int) (addresses.get(0).getLatitude() * 1E6), 
                        (int) (addresses.get(0).getLongitude() * 1E6));
                mc.animateTo(p);    
                mapView.invalidate();
            }    
        } catch (IOException e) {
            e.printStackTrace();
        }
Once the location is found, the above code navigates the map to the location. Figure 12 shows the code in action.

Figure 12 Navigating to the Empire State Building

Summary

In this article, you have learnt a few tricks for the Google Maps in Android. Using Google Maps, there are many interesting projects you can work on, such as geo-tagging, geo-tracking, etc. If you have cool ideas on building cool location-based services, share with us in the comments box below. Have fun!


Reff : http://mobiforge.com/developing/story/using-google-maps-android