Belajar Android GoogleMaps V2 kali ini akan membahas tentang cara mencari alamat dengan menggunakan Geocoder service. Kalau pada tutorial yang lalu kita mampu menampilkan Alamat dari suatu titik, Pada tutorial ini adalah kebalikannya. Mari kita mulai.
1. Buat Project dengan nama “LearnGeocoderMaspV2” dan packagenya dengan nama “com.batikmob.learngeocodermaspv2”
2. Seperti biasa yang pertama kalai kita sentuh adalah bagian layout, edit main_activity.xml lalu ketikan kode berikut
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/RelativeLayout1" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <EditText android:id="@+id/editTextPlace" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_toLeftOf="@+id/buttonSearch" android:ems="10" android:gravity="top" android:hint="place name" > </EditText> <Button android:id="@+id/buttonSearch" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:gravity="top" android:text="Search" /> <fragment android:id="@+id/mapgeocode" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@+id/buttonSearch" class="com.google.android.gms.maps.SupportMapFragment" > </fragment> </RelativeLayout>
3. Buat Class baru dengan nama “GeocodeJSONParser.java” lalu ketikan kode berikut
package com.batikmob.learngeocodermaspv2; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class GeocodeJSONParser { public List<HashMap<String,String>> parse(JSONObject jObject){ JSONArray jPlaces = null; try { jPlaces = jObject.getJSONArray("results"); } catch (JSONException e) { e.printStackTrace(); } return getPlaces(jPlaces); } private List<HashMap<String, String>> getPlaces(JSONArray jPlaces){ int placesCount = jPlaces.length(); List<HashMap<String, String>> placesList = new ArrayList<HashMap<String,String>>(); HashMap<String, String> place = null; /** Taking each place, parses and adds to list object */ for(int i=0; i<placesCount;i++){ try { /** Call getPlace with place JSON object to parse the place */ place = getPlace((JSONObject)jPlaces.get(i)); placesList.add(place); } catch (JSONException e) { e.printStackTrace(); } } return placesList; } private HashMap<String, String> getPlace(JSONObject jPlace){ HashMap<String, String> place = new HashMap<String, String>(); String formatted_address = "-NA-"; String lat=""; String lng=""; try { // Extracting formatted address, if available if(!jPlace.isNull("formatted_address")){ formatted_address = jPlace.getString("formatted_address"); } lat = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lat"); lng = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lng"); place.put("formatted_address", formatted_address); place.put("lat", lat); place.put("lng", lng); } catch (JSONException e) { e.printStackTrace(); } return place; } }
4. Edit class MainActivity.java lalu ketikan kode berikut
package com.batikmob.learngeocodermaspv2; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.HashMap; import java.util.List; import org.json.JSONObject; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; public class MainActivity extends FragmentActivity { private Button btnSearch; private GoogleMap mMap; private EditText edtPlace; private static final String TAG="MainActivity"; static final LatLng INDONESIA = new LatLng(-6.29436, 106.8859); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnSearch = (Button) findViewById(R.id.buttonSearch); SupportMapFragment mapFragment = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.mapgeocode); // Getting reference to the Google Map mMap = mapFragment.getMap(); mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(INDONESIA,5)); edtPlace = (EditText) findViewById(R.id.editTextPlace); // Setting click event listener for the find button btnSearch.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub String place_name = edtPlace.getText().toString(); if(place_name==null || place_name.equals("")){ Toast.makeText(getBaseContext(), "No Place is entered", Toast.LENGTH_SHORT).show(); return; } String url = "https://maps.googleapis.com/maps/api/geocode/json?"; try { // encoding special characters like space in the user input place place_name = URLEncoder.encode(place_name, "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } String address = "address=" + place_name; String sensor = "sensor=false"; // url , from where the geocoding data is fetched url = url + address + "&" + sensor; Log.v(TAG+"onClick", "url is: "+url); // String modifiedURL= url.toString().replace(" ", "%20"); // Instantiating DownloadTask to get places from Google Geocoding service // in a non-ui thread DownloadTask downloadTask = new DownloadTask(); // Start downloading the geocoding places downloadTask.execute(url); } }); } private String downloadUrl(String strUrl) throws IOException{ String data = ""; InputStream iStream = null; HttpURLConnection urlConnection = null; try{ URL url = new URL(strUrl); // Creating an http connection to communicate with url urlConnection = (HttpURLConnection) url.openConnection(); // Connecting to url urlConnection.connect(); // Reading data from url iStream = urlConnection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(iStream)); StringBuffer sb = new StringBuffer(); String line = ""; while( ( line = br.readLine()) != null){ sb.append(line); } data = sb.toString(); br.close(); }catch(Exception e){ Log.d("Exception while downloading url", e.toString()); }finally{ iStream.close(); urlConnection.disconnect(); } return data; } /** A class, to download Places from Geocoding webservice */ private class DownloadTask extends AsyncTask<String, Integer, String>{ String data = null; // Invoked by execute() method of this object @Override protected String doInBackground(String... url) { try{ data = downloadUrl(url[0]); }catch(Exception e){ Log.d("Background Task",e.toString()); } return data; } // Executed after the complete execution of doInBackground() method @Override protected void onPostExecute(String result){ ParserTask parserTask = new ParserTask(); parserTask.execute(result); } } class ParserTask extends AsyncTask<String, Integer, List<HashMap<String,String>>>{ JSONObject jObject; @Override protected List<HashMap<String,String>> doInBackground(String... jsonData) { List<HashMap<String, String>> places = null; GeocodeJSONParser parser = new GeocodeJSONParser(); try{ jObject = new JSONObject(jsonData[0]); /** Getting the parsed data as a an ArrayList */ places = parser.parse(jObject); }catch(Exception e){ Log.d("Exception",e.toString()); } return places; } // Executed after the complete execution of doInBackground() method @Override protected void onPostExecute(List<HashMap<String,String>> list){ // Clears all the existing markers mMap.clear(); for(int i=0;i<list.size();i++){ // Creating a marker MarkerOptions markerOptions = new MarkerOptions(); HashMap<String, String> hmPlace = list.get(i); double lat = Double.parseDouble(hmPlace.get("lat")); double lng = Double.parseDouble(hmPlace.get("lng")); String name = hmPlace.get("formatted_address"); LatLng latLng = new LatLng(lat, lng); markerOptions.position(latLng); markerOptions.title(name); mMap.addMarker(markerOptions); // Locate the first location if(i==0) mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng)); } } } }
5. Edit AndroidManifest.xml lalu ketikan kode berikut
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.batikmob.learngeocodermaspv2" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <permission android:name="com.batikmob.learngeocodermaspv2.permission.MAPS_RECEIVE" android:protectionLevel="signature" /> <uses-feature android:glEsVersion="0x00020000" android:required="true" /> <uses-permission android:name="com.batikmob.learngeocodermaspv2.permission.MAPS_RECEIVE" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.batikmob.learngeocodermaspv2.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="AIzaSyAOr7w4HA1_TGZEyM6MKQz56dB7tDwH08w" /> </application> </manifest>
6. Run Project, pada place name ketikan bandung
Demo Geocoder Android Googlemaps v2
Belajar Android memang menyenangkan yah 🙂
Semoga Bermanfaat
Salam Hangat
Agus Haryanto
Referens:
http://sunil-android.blogspot.com/2013/07/google-map-android-api-v2-with-location.html
Mas agus..
ada ga tutorial android yang mengambil posisi LAT dan ING nya diambil dari TEXTFIELD?
jadi ga diinput langsung dari listning.. 🙂 jadi diinput manual di textfield nya kemudian klik tombol prosesnya kemudian muncul petax, trus ada penentuan jarak terdekat gitu..
trimakasih..
salam android.. ^^
mohon balasannya…
@Edwin, Seharusnya lebih mudah, karena kita tinggal isi latitude dan longitudenya di EditText lalu kita tanggkap isinya dan proses
baik mas.. 🙂
trimakasih,
tapi bagaimana jika ditambahkan tombol proses? saat tombol di klik maka akan muncul layout ke-2 nya, yang menampilkan peta posisi lat dan Ing nya?
maaf ms newbie.. 😀
@Edwin, Coba belajar tentang Explicit Intent diandroid, diblog ini juga ada kok artikelnya
baikkkkk mas…… trimksih bnyaak… 🙂 🙂
@edwin kalo mau pake jarak terdekat bisa pake rumus haversine mas,
terimakasih gan buat alat bantu tugas akhir saya gan hatur nuhun
banyak pentungnya mas -_- tapi udah saya benerin dengan membuat class (yang silang saya klik dan pilih atas sendiri) terus udaj bener..
nih ada lagi yang sangat membingungkan saya mas.. errornya disini >> SupportMapFragment mapFragment = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.mapgeocode);
mohon supportnya mas 🙂 hehehe
buat tugas akhir ane, padahal (masih) smk 🙁
entah class yang saya buat asal-asalan itu bisa apa enggak ya mas.. mohon bantuannya
thanks
sama dengan saya mas errornya 🙁
error disini
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
private GoogleMap mMap;
static final LatLng INDONESIA = new LatLng(-6.29436, 106.8859);
SupportMapFragment mapFragment = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.mapgeocode);
mMap = mapFragment.getMap();
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(INDONESIA,5));
mMap.clear();
MarkerOptions markerOptions = new MarkerOptions();
LatLng latLng = new LatLng(lat, lng);
mMap.addMarker(markerOptions);
if(i==0) mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
solusinya ane tunggu mas 🙁
udah gak error, ternyata belum saya add librarynya… udah bener semua, gak ada error/pentung, tapi kok forse closed ya? mohon bantuannya mas 🙂 saya butuh banget ini mas… buat tugas akhir psg saya……
klo untuk nentuin jarak terdekat,,bagaimna di map v2?