This example explains how we can convert latitude longitude values to corresponding address. The process is called Reverse geocoding.
Algorithm:
1.) Create a new project by File-> New -> Android Project name it Gecoding-example.
2.) You will see some default code into your main.xml and android manifest file.
3.) Add internet permission to your manifest file or write following in android.manifest file:
2.) You will see some default code into your main.xml and android manifest file.
3.) Add internet permission to your manifest file or write following in android.manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.geocoding"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="7" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.geocoding"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="7" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".GecodingActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
<activity android:name=".GecodingActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
4.) Write following into main.xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Send Latitute and Longitite from simulator or you will get some values when you navigate your device from one location to another while this app is running"
android:id="@+id/textView1" />
<TextView android:text="Set Latitude:" android:layout_width="fill_parent"
android:layout_height="wrap_content"android:layout_below="@+id/textView1"
android:layout_alignParentLeft="true"android:layout_marginTop="54dp"
android:id="@+id/textView2"></TextView>
<TextView android:layout_width="wrap_content"android:layout_below="@+id/textView2"
android:layout_height="wrap_content"android:id="@+id/txtLatitude"></TextView>
<TextView android:text="Set Longitude:"android:layout_width="wrap_content"
android:id="@+id/TextView01" android:layout_height="wrap_content"
android:layout_below="@+id/txtLatitude"android:layout_alignParentLeft="true"
android:layout_marginTop="30dp"></TextView>
<TextView android:layout_width="wrap_content"android:layout_below="@+id/TextView01"
android:layout_height="wrap_content"android:id="@+id/txtLongitude"></TextView>
android:layout_height="wrap_content"
android:text="Send Latitute and Longitite from simulator or you will get some values when you navigate your device from one location to another while this app is running"
android:id="@+id/textView1" />
<TextView android:text="Set Latitude:" android:layout_width="fill_parent"
android:layout_height="wrap_content"android:layout_below="@+id/textView1"
android:layout_alignParentLeft="true"android:layout_marginTop="54dp"
android:id="@+id/textView2"></TextView>
<TextView android:layout_width="wrap_content"android:layout_below="@+id/textView2"
android:layout_height="wrap_content"android:id="@+id/txtLatitude"></TextView>
<TextView android:text="Set Longitude:"android:layout_width="wrap_content"
android:id="@+id/TextView01" android:layout_height="wrap_content"
android:layout_below="@+id/txtLatitude"android:layout_alignParentLeft="true"
android:layout_marginTop="30dp"></TextView>
<TextView android:layout_width="wrap_content"android:layout_below="@+id/TextView01"
android:layout_height="wrap_content"android:id="@+id/txtLongitude"></TextView>
<Button android:text="Show Address" android:layout_width="wrap_content"
android:layout_height="wrap_content"android:id="@+id/btnReverseGeocode"
android:layout_below="@+id/textView1"android:layout_toRightOf="@+id/TextView01"
android:layout_marginTop="172dp"></Button>
</RelativeLayout>
android:layout_height="wrap_content"android:id="@+id/btnReverseGeocode"
android:layout_below="@+id/textView1"android:layout_toRightOf="@+id/TextView01"
android:layout_marginTop="172dp"></Button>
</RelativeLayout>
5.) Create Geocoder.java and write following into it:
package com.example.geocoding;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import org.xml.sax.XMLReader;
import android.location.Location;
public class Geocoder
{
public static String reverseGeocode(Location loc)
{
String localityName = "";
HttpURLConnection connection = null;
URL serverAddress = null;
try
{
serverAddress = new URL("http://maps.google.com/maps/geo?q=" +Double.toString(loc.getLatitude()) + "," + Double.toString(loc.getLongitude()) +
"&output=xml&oe=utf8&sensor=true&key=0jp8vWjNayJISFKdvcJwGmwsjgoCoQrT_dflCfQ");
connection = null;
connection =(HttpURLConnection)serverAddress.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setReadTimeout(10000);
connection.connect();
try
{
InputStreamReader isr = newInputStreamReader(connection.getInputStream());
InputSource source = new InputSource(isr);
SAXParserFactory factory =SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader xr = parser.getXMLReader();
GoogleReverseGeocodeXmlHandler handler = newGoogleReverseGeocodeXmlHandler();
xr.setContentHandler(handler);
xr.parse(source);
localityName = handler.getLocalityName();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
return localityName;
}
}
{
public static String reverseGeocode(Location loc)
{
String localityName = "";
HttpURLConnection connection = null;
URL serverAddress = null;
try
{
serverAddress = new URL("http://maps.google.com/maps/geo?q=" +Double.toString(loc.getLatitude()) + "," + Double.toString(loc.getLongitude()) +
"&output=xml&oe=utf8&sensor=true&key=0jp8vWjNayJISFKdvcJwGmwsjgoCoQrT_dflCfQ");
connection = null;
connection =(HttpURLConnection)serverAddress.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setReadTimeout(10000);
connection.connect();
try
{
InputStreamReader isr = newInputStreamReader(connection.getInputStream());
InputSource source = new InputSource(isr);
SAXParserFactory factory =SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader xr = parser.getXMLReader();
GoogleReverseGeocodeXmlHandler handler = newGoogleReverseGeocodeXmlHandler();
xr.setContentHandler(handler);
xr.parse(source);
localityName = handler.getLocalityName();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
return localityName;
}
}
6.) Create GoogleReverseGeocodeXmlHandler.java and write following into it:
package com.example.geocoding;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class GoogleReverseGeocodeXmlHandler extends DefaultHandler
{
private boolean inLocalityName = false;
private boolean finished = false;
private StringBuilder builder;
private String localityName;
public String getLocalityName()
{
return this.localityName;
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
super.characters(ch, start, length);
if (this.inLocalityName && !this.finished)
{
if ((ch[start] != ‘\n‘) && (ch[start] != ‘ ‘))
{
builder.append(ch, start, length);
}
}
}
{
private boolean inLocalityName = false;
private boolean finished = false;
private StringBuilder builder;
private String localityName;
public String getLocalityName()
{
return this.localityName;
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
super.characters(ch, start, length);
if (this.inLocalityName && !this.finished)
{
if ((ch[start] != ‘\n‘) && (ch[start] != ‘ ‘))
{
builder.append(ch, start, length);
}
}
}
@Override
public void endElement(String uri, String localName, String name)
throws SAXException
{
super.endElement(uri, localName, name);
if (!this.finished)
{
if (localName.equalsIgnoreCase("LocalityName"))
{
this.localityName = builder.toString();
this.finished = true;
}
if (builder != null)
{
builder.setLength(0);
}
}
}
public void endElement(String uri, String localName, String name)
throws SAXException
{
super.endElement(uri, localName, name);
if (!this.finished)
{
if (localName.equalsIgnoreCase("LocalityName"))
{
this.localityName = builder.toString();
this.finished = true;
}
if (builder != null)
{
builder.setLength(0);
}
}
}
@Override
public void startDocument() throws SAXException
{
super.startDocument();
builder = new StringBuilder();
}
public void startDocument() throws SAXException
{
super.startDocument();
builder = new StringBuilder();
}
@Override
public void startElement(String uri, String localName, String name,Attributes attributes) throws SAXException
{
super.startElement(uri, localName, name, attributes);
if (localName.equalsIgnoreCase("LocalityName"))
{
this.inLocalityName = true;
}
}
}
public void startElement(String uri, String localName, String name,Attributes attributes) throws SAXException
{
super.startElement(uri, localName, name, attributes);
if (localName.equalsIgnoreCase("LocalityName"))
{
this.inLocalityName = true;
}
}
}
7.) Make sure to change the google api key you created on your system.
8.) Run for output.
8.) Run for output.
Steps:
1.) Create a project named Gecoding-example and set the information as stated in the image.
Build Target: Android 2.1 (Google API)
Application Name: Gecoding-example
Package Name: com.example. Gecoding
Activity Name: GecodingActivity
Min SDK Version: 7
Application Name: Gecoding-example
Package Name: com.example. Gecoding
Activity Name: GecodingActivity
Min SDK Version: 7
2.) Open GecodingActivity.java file and write following code there:
package com.example.geocoding;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class GecodingActivity extends Activity {
private LocationManager locationManager;
private Location currentLocation;
private TextView txtLatitude;
private TextView txtLongitude;
private Button btnReverseGeocode;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txtLatitude = (TextView) findViewById(R.id.txtLatitude);
txtLongitude = (TextView) findViewById(R.id.txtLongitude);
btnReverseGeocode = (Button) findViewById(R.id.btnReverseGeocode);
btnReverseGeocode.setOnClickListener(
new OnClickListener() {
public void onClick(View v)
{
handleReverseGeocodeClick();
}
}
);
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates("gps", (long)30000, (float) 10.0,new LocationListener()
{
public void onLocationChanged(Location arg0)
{
handleLocationChanged(arg0);
}
public void onProviderDisabled(String arg0) {
}
public void onProviderEnabled(String arg0) {
}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
});
}
private void handleLocationChanged(Location loc)
{
this.currentLocation = loc;
this.txtLatitude.setText(Double.toString(loc.getLatitude()));
this.txtLongitude.setText(Double.toString(loc.getLongitude()));
}
private void handleReverseGeocodeClick()
{
if (this.currentLocation != null)
{
ReverseGeocodeLookupTask task = new ReverseGeocodeLookupTask();
task.applicationContext = this;
task.execute();
}
else
{
Toast.makeText(this,"Please wait until we have a location fix from the gps",Toast.LENGTH_SHORT).show();
}
}
public class ReverseGeocodeLookupTask extends AsyncTask <Void, Void, String>
{
private ProgressDialog dialog;
protected Context applicationContext;
@Override
protected void onPreExecute()
{
this.dialog = ProgressDialog.show(applicationContext, "Please wait…",
"Requesting for the location address you entered", true);
}
@Override
protected String doInBackground(Void… params)
{
String localityName = "";
if (currentLocation != null)
{
localityName =Geocoder.reverseGeocode(currentLocation);
}
return localityName;
}
@Override
protected void onPostExecute(String result)
{
this.dialog.cancel();
Toast.makeText(applicationContext,"Your Locality is: " +result,Toast.LENGTH_LONG).show();
}
}
}
private LocationManager locationManager;
private Location currentLocation;
private TextView txtLatitude;
private TextView txtLongitude;
private Button btnReverseGeocode;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txtLatitude = (TextView) findViewById(R.id.txtLatitude);
txtLongitude = (TextView) findViewById(R.id.txtLongitude);
btnReverseGeocode = (Button) findViewById(R.id.btnReverseGeocode);
btnReverseGeocode.setOnClickListener(
new OnClickListener() {
public void onClick(View v)
{
handleReverseGeocodeClick();
}
}
);
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates("gps", (long)30000, (float) 10.0,new LocationListener()
{
public void onLocationChanged(Location arg0)
{
handleLocationChanged(arg0);
}
public void onProviderDisabled(String arg0) {
}
public void onProviderEnabled(String arg0) {
}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
});
}
private void handleLocationChanged(Location loc)
{
this.currentLocation = loc;
this.txtLatitude.setText(Double.toString(loc.getLatitude()));
this.txtLongitude.setText(Double.toString(loc.getLongitude()));
}
private void handleReverseGeocodeClick()
{
if (this.currentLocation != null)
{
ReverseGeocodeLookupTask task = new ReverseGeocodeLookupTask();
task.applicationContext = this;
task.execute();
}
else
{
Toast.makeText(this,"Please wait until we have a location fix from the gps",Toast.LENGTH_SHORT).show();
}
}
public class ReverseGeocodeLookupTask extends AsyncTask <Void, Void, String>
{
private ProgressDialog dialog;
protected Context applicationContext;
@Override
protected void onPreExecute()
{
this.dialog = ProgressDialog.show(applicationContext, "Please wait…",
"Requesting for the location address you entered", true);
}
@Override
protected String doInBackground(Void… params)
{
String localityName = "";
if (currentLocation != null)
{
localityName =Geocoder.reverseGeocode(currentLocation);
}
return localityName;
}
@Override
protected void onPostExecute(String result)
{
this.dialog.cancel();
Toast.makeText(applicationContext,"Your Locality is: " +result,Toast.LENGTH_LONG).show();
}
}
}
3.) Compile and build the project.
4.) Send some latitude longitude values if running on simulator for the output.
4.) Send some latitude longitude values if running on simulator for the output.
No comments:
Post a Comment