You are on page 1of 16

1) 2) 3) 4) 5) 6)

Create app with package name com.example.abad.gdgmap Create following classes LbsGeocodingActivity.java(Acitivity) Create a class name Place,java, Create an activity name ShowMapActivity.java(FragmentActivity)
Add two xml file in menu folder (activity_show_map.xml, options.xml)

Copy code for each class from word doc.

LbsGeocodingActivity.java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URI; import java.util.ArrayList; import java.util.List; import java.util.Locale; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONObject; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.location.Location; import android.location.Address; import android.location.Geocoder; import android.location.LocationListener; import android.location.LocationManager; import android.os.AsyncTask; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.TextView; import android.widget.Toast; public class LbsGeocodingActivity extends Activity {

private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds protected LocationManager locationManager; protected Button mapit; protected TextView tv; protected EditText et; String address = null; Double lat = null; Double lng = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mapit = (Button) findViewById(R.id.btn_map); tv = (TextView)findViewById(R.id.tv); et = (EditText) findViewById(R.id.et);

/* locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, MINIMUM_TIME_BETWEEN_UPDATES, MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, new MyLocationListener() );*/ mapit.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { address = et.getText().toString(); System.out.println("Address:" + address); if(address == null || address.toString().isEmpty() ) { Toast.makeText(LbsGeocodingActivity.this, "Empty", Toast.LENGTH_LONG).show(); } else { showCurrentLocation(); } } }); //

} //onCreate protected void showCurrentLocation() { // Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); String locations = null; /* if (location != null) { String message = String.format( "Current Location \n Longitude: %1$s \n Latitude: %2$s", location.getLongitude(), location.getLatitude());*/ //transfer control to map activity with current lat,long /* Intent i = new Intent (this,ShowMapActivity.class); i.putExtra("lat", location.getLatitude()); i.putExtra("long", location.getLongitude()); // startActivity(i);*/ // Toast.makeText(LbsGeocodingActivity.this, message,Toast.LENGTH_LONG).show();

//-----------AsyncTask<String, Void, String> stringVoidVoidAsyncTask = new AsyncTask<String, Void, String>() {

@Override protected void onPostExecute(String result) { // TODO Auto-generated method stub if(result != null) { tv.setText("Results Found: " + result); String[] str = result.split(","); lat = Double.parseDouble(str[0]); lng = Double.parseDouble(str[1]);

Intent i = new Intent (LbsGeocodingActivity.this,ShowMapActivity.class); i.putExtra("lat", str[0]); i.putExtra("lng", str[1]); startActivity(i); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); } else {

tv.setText("Results Not Found: "); } //place=result; super.onPostExecute(result); } BufferedReader in; @Override protected String doInBackground(String... strings) { String url = ""; String locations = "" ; if (strings.length > 0) { url = strings[0]; } else { return null; } try { HttpClient httpClient = new DefaultHttpClient();// Client HttpGet getRequest = new HttpGet(); getRequest.setURI(new URI(url)); // HttpPost postRequest = new HttpPost(); // postRequest.setURI(new URI(url)); HttpResponse response = httpClient.execute(getRequest); in = new BufferedReader (new InputStreamReader(response.getEntity().getContent())); StringBuffer sb = new StringBuffer(""); String line = ""; String NL = System.getProperty("line.separator"); while ((line = in.readLine()) != null) { sb.append(line + NL); } in.close(); String page = sb.toString(); JSONObject jsonObject = new JSONObject(page); JSONArray jsonArray = (JSONArray) jsonObject.get("results"); if (jsonArray.length() > 0) { jsonObject = (JSONObject) jsonArray.get(0); jsonObject = (JSONObject) jsonObject.get("geometry"); JSONObject location = (JSONObject) jsonObject.get("location"); Double lat = (Double) location.get("lat");

Double lng = (Double) location.get("lng"); System.out.println("lat - " + lat + " , lon - " + lng); return String.valueOf(lat)+","+String.valueOf(lng); } // System.out.println(page); return String.valueOf(lat)+","+String.valueOf(lng); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } return String.valueOf(lat)+","+String.valueOf(lng); } };

//String current = String.format("%1$s,%2$s",location.getLongitude(), location.getLatitude()); //geocoding API - sending address to get lat long

stringVoidVoidAsyncTask.execute("http://maps.googleapis.com/maps/api/geocode/json?addres s=" + address + "&sensor=true"); //23.0333,72.6167 } } ----------------------------------------------------------------------------------------------------------Place.java

import java.io.Serializable;

public class Place { public double getLat() { return lat; } public void setLat(double lat) { this.lat = lat;

} public double getLng() { return lng; } public void setLng(double lng) { this.lng = lng; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getReference() { return reference; } public void setReference(String reference) { this.reference = reference; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } public String getVicinity() { return vicinity; } public void setVicinity(String vicinity) { this.vicinity = vicinity; }

public String getFormatted_address() { return formatted_address; } public void setFormatted_address(String formatted_address) { this.formatted_address = formatted_address; }

public String getFormatted_phone_number() { return formatted_phone_number; } public void setFormatted_phone_number(String formatted_phone_number) { this.formatted_phone_number = formatted_phone_number; } public String id; public String name; public double lat; public double lng; public String reference; public String icon; public String vicinity; public String formatted_address;

public String formatted_phone_number; @Override public String toString() { return name + " - " + id + " - " + reference; }

} ---------------------------------------------ShowMapActivity.java

package com.example.abad.gdgmap; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URI; import java.util.List; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONObject; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.location.Address;

import android.location.Geocoder; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.TextView; import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.GoogleMap.OnMapClickListener; import com.google.android.gms.maps.MapFragment; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.common.GooglePlayServicesUtil; public class ShowMapActivity extends FragmentActivity implements OnMapClickListener { GoogleMap map; Toast t; LatLng LOCAL = new LatLng(0,0); int searchtype=0; TextView tv_loc = null; MarkerOptions markerOptions; LatLng location = null; protected LatLng latLng; Place place = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); try { int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext()); // Showing status if(status==ConnectionResult.SUCCESS) { setContentView(R.layout.activity_show_map); tv_loc = (TextView) findViewById(R.id.tv_loc); // Getting status SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

// Getting a reference to the map map = supportMapFragment.getMap(); Float lat = Float.valueOf(getIntent().getStringExtra("lat")); Float lng = Float.valueOf(getIntent().getStringExtra("lng")); // System.out.println(getIntent().getStringExtra("lat")+ ":" +getIntent().getStringExtra("lng") ); LOCAL = new LatLng(lat,lng); Marker mylocation = map.addMarker(new MarkerOptions().position(LOCAL) .title("Here") .icon(BitmapDescriptorFactory.defaultMarker(60))); // Move the camera instantly to Local with a zoom of 15. map.moveCamera(CameraUpdateFactory.newLatLngZoom(LOCAL, 2)); // Zoom in, animating the camera. map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null); map.setTrafficEnabled(true); if(searchtype ==0 ) { map.setMapType(GoogleMap.MAP_TYPE_HYBRID); } // Setting a click event handler for the map map.setOnMapClickListener(this);

} else{ int requestCode = 10; Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode); dialog.show(); } }catch(Exception e) { t.makeText(this,e.toString(), 1).show(); } } //end onCreate public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.options, menu); return true; } public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.hybrid: map.setMapType(GoogleMap.MAP_TYPE_HYBRID); return true;

case R.id.terrain: map.setMapType(GoogleMap.MAP_TYPE_TERRAIN); return true; case R.id.satelite: map.setMapType(GoogleMap.MAP_TYPE_SATELLITE); return true; case R.id.normal: map.setMapType(GoogleMap.MAP_TYPE_NORMAL); return true; default: return super.onOptionsItemSelected(item); } } @Override public void onMapClick(LatLng arg0) { // Getting the Latitude and Longitude of the touched location latLng = arg0; // tv_loc.setText(String.valueOf(latLng.latitude)+ "," + String.valueOf(latLng.longitude)); // Clears the previously touched position map.clear(); // Animating to the touched position map.animateCamera(CameraUpdateFactory.newLatLng(latLng)); // Creating a marker markerOptions = new MarkerOptions(); // Setting the position for the marker markerOptions.position(latLng); // Placing a marker on the touched position map.addMarker(markerOptions); // Adding Marker on the touched location with address ReverseGeocode(); } protected void ReverseGeocode() { //-----------AsyncTask<String, Void, String> stringVoidstringAsyncTask = new AsyncTask<String, Void, String>() { @Override protected void onPostExecute(String result) { // TODO Auto-generated method stub if(result != null) { tv_loc.setText("Results Found: " + result); } else { tv_loc.setText("Results Found: ");

} super.onPostExecute(result); } BufferedReader in; @Override protected String doInBackground(String... strings) { String url = ""; String locations = "" ; String name=""; if (strings.length > 0) { url = strings[0]; } else { return null; } try { HttpClient httpClient = new DefaultHttpClient();// Client HttpGet getRequest = new HttpGet(); getRequest.setURI(new URI(url)); // HttpPost postRequest = new HttpPost(); // postRequest.setURI(new URI(url)); HttpResponse response = httpClient.execute(getRequest); in = new BufferedReader (new InputStreamReader(response.getEntity().getContent())); StringBuffer sb = new StringBuffer(""); String line = ""; String NL = System.getProperty("line.separator"); while ((line = in.readLine()) != null) { sb.append(line + NL); } in.close(); String page = sb.toString(); JSONObject jsonObject = new JSONObject(page); JSONArray jsonArray = (JSONArray) jsonObject.get("results"); if (jsonArray.length() > 0) { for(int i=0; i < jsonArray.length(); i++) { jsonObject = (JSONObject) jsonArray.get(i); name = (String) jsonObject.get("formatted_address"); Place p = new Place(); p.setName(name); jsonObject = (JSONObject) jsonObject.get("geometry"); JSONObject location = (JSONObject) jsonObject.get("location");

Double lat = (Double) location.get("lat"); Double lng = (Double) location.get("lng"); p.setLat(lat); p.setLng(lng); locations += p.name + "\n" + p.lat + "," + p.lng + "\n" ; } //end for }// end if System.out.println(locations); return name; } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } return name; } //end doinbackgroud };

String current = String.format("%1$s,%2$s", latLng.latitude,latLng.longitude);

stringVoidstringAsyncTask.execute("http://maps.googleapis.com/maps/api/geocode/json?addre ss="+current +"&sensor=true"); //23.0333,72.6167 } }

------------------------------------------------------------------------------------------------------activity_show_map.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity" >

<TextView android:id="@+id/tv_loc" android:layout_width="match_parent" android:layout_height="wrap_content" /> <fragment xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/map" android:layout_width="match_parent" android:layout_height="match_parent" class="com.google.android.gms.maps.SupportMapFragment" />

</LinearLayout> -----------------------------------main.xml

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:id="@+id/tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Address" /> <EditText android:id="@+id/et" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10"

android:hint="Enter Address" > <requestFocus /> </EditText> <Button android:id="@+id/btn_map" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Map It" />

</LinearLayout> --------------------------------------

activity_show_map.xml(menu code)

<menu xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@+id/menu_settings" android:orderInCategory="100" android:showAsAction="never" android:title="options"/>

</menu> ------------------------------------------options.xml

<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@+id/hybrid" android:title="hybrid"></item> <item android:id="@+id/satelite" android:title="satelite"></item> <item android:id="@+id/terrain" android:title="terrain"></item> <item android:id="@+id/normal" android:title="normal"></item>

</menu> ---------------------------------------------------AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.abad.gdgmap" android:versionCode="1" android:versionName="1.0" >

<uses-sdk android:minSdkVersion="16" android:targetSdkVersion="16" />

<permission android:name="com.example.abad.gdgmap.permission.MAPS_RECEIVE" android:protectionLevel="signature" /> <uses-feature android:glEsVersion="0x00020000" android:required="true" /> <uses-permission android:name="com.example.abad.gdgmap.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" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.abad.gdgmap.LbsGeocodingActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="com.example.abad.gdgmap.ShowMapActivity" android:label="@string/app_name" > </activity> <activity android:name="com.example.abad.gdgmap.Directions" android:label="@string/app_name" > </activity> <activity android:name="com.example.abad.gdgmap.AndroidLocationAcitivity" android:label="@string/app_name" > </activity> <meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="AIzaSyAT3Rp61H91R-oUW58KsB5s3bNLWYUaFc8" /> </application> </manifest>

You might also like