Friday, February 11, 2011

Get location(Latitude and Longitude) from described address using Geocoder

The method getFromLocationName(String locationName, int maxResults) returns an array of Addresses that are known to describe the named location.

The query will block and returned values will be obtained by means of a network lookup. The results are a best guess and are not guaranteed to be meaningful or correct. It may be useful to call this method from a thread separate from your primary UI thread.

Modify the last exercise "Get list of address from location using Geocoder", the returned address of the clicked item is passed to getFromLocationName(), to get the location(Latitude and Longitude).

Suggest to test on true device. In my tests, it doesn't always work on emulator!


Get location(Latitude and Longitude) from described address using Geocoder

<?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:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="@string/hello"
  />
<TextView
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="Location"
  android:background="#505050"
  />
<TextView
  android:id="@+id/mylatitude"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  />
<TextView
  android:id="@+id/mylongitude"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  />
<TextView
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="Address"
  android:background="#505050"
  />
<TextView
  android:id="@+id/myaddress"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  />
<Spinner
  android:id="@+id/addresslist"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  />
<TextView
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="Returned Address"
  android:background="#505050"
  />
<TextView
  android:id="@+id/returnedaddress"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  />
<TextView
  android:id="@+id/returnedlatitude"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  />
<TextView
  android:id="@+id/returnedlongitude"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  />
</LinearLayout>


package com.exercise.AndroidFromLocation;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class AndroidFromLocation extends Activity {

double LATITUDE = 37.42233;
double LONGITUDE = -122.083;

final int maxResult =5;
String addressList[] = new String[maxResult];
private ArrayAdapter<String> adapter;

TextView myReturnedAddress, myReturnedLatitude, myReturnedLongitude;

Geocoder geocoder;

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
      TextView myLatitude = (TextView)findViewById(R.id.mylatitude);
      TextView myLongitude = (TextView)findViewById(R.id.mylongitude);
      TextView myAddress = (TextView)findViewById(R.id.myaddress);
      Spinner myAddressList = (Spinner)findViewById(R.id.addresslist);
      myReturnedAddress = (TextView)findViewById(R.id.returnedaddress);
      myReturnedLatitude = (TextView)findViewById(R.id.returnedlatitude);
      myReturnedLongitude = (TextView)findViewById(R.id.returnedlongitude);
    
      myLatitude.setText("Latitude: " + String.valueOf(LATITUDE));
      myLongitude.setText("Longitude: " + String.valueOf(LONGITUDE));
    
      geocoder = new Geocoder(this, Locale.ENGLISH);

      try {
  List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, maxResult);
 
  if(addresses != null) {
  
   for (int j=0; j<maxResult; j++){
    Address returnedAddress = addresses.get(j);
    StringBuilder strReturnedAddress = new StringBuilder();
    for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
     strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
    }
    addressList[j] = strReturnedAddress.toString();
   }
  
   adapter = new ArrayAdapter<String>(this,
     android.R.layout.simple_spinner_item, addressList);
   adapter.setDropDownViewResource(android.R.layout.
     simple_spinner_dropdown_item);
   myAddressList.setAdapter(adapter);
  
   myAddressList.setOnItemSelectedListener(myAddressListOnItemSelectedListener);
  }
  else{
   myAddress.setText("No Address returned!");
  }
 } catch (IOException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
  myAddress.setText("Canont get Address!");
 }
  }

  Spinner.OnItemSelectedListener myAddressListOnItemSelectedListener
  = new Spinner.OnItemSelectedListener(){

 @Override
 public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
   long arg3) {
  // TODO Auto-generated method stub

  myReturnedAddress.setText(addressList[arg2]);
 
  try {
   List<Address> returnedaddresses = geocoder.getFromLocationName(addressList[arg2], 1);
  
   if(returnedaddresses != null){
    myReturnedLatitude.setText(String.valueOf(returnedaddresses.get(0).getLatitude()));
          myReturnedLongitude.setText(String.valueOf(returnedaddresses.get(0).getLongitude()));
   }
  
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }

 @Override
 public void onNothingSelected(AdapterView<?> arg0) {
  // TODO Auto-generated method stub
 
 }};
}


Download the files.

Updated@20150916:
Find addresses of given latitude and longitude using android.location.Geocoder
Example allow users to enter latitude and longitude, then find the addresses that are known to describe the area immediately surrounding the given latitude and longitude,

21 comments:

  1. i have tried this code but it does not work for me.when i try to run force close error comes.

    ReplyDelete
  2. hello new,

    Make sure the "3G" icon is on, it need online service.

    ReplyDelete
  3. Hi, I am beginner to Android and I want to get just lacation (lat and long). How can i do that?
    Thanks...

    ReplyDelete
  4. hello Erol,

    Check the code, returnedaddresses.get(0).getLatitude() and returnedaddresses.get(0).getLongitude() are the returned lat and long.

    ReplyDelete
  5. hi! i get 'cannot get address' on emulator
    and the logcat says:
    service not available
    why is that..is it because of 3g like u said before?if yes,how to turn it on ?does exist in emulator?

    ReplyDelete
  6. +++ i have this icon 3G on emulator like in the example

    ReplyDelete
  7. do i have to set the location i am right now..?i suppose the locaation of the example is of your place..i live in greece so i have to set it different

    ReplyDelete
  8. hello dimitrismidas,

    Just re-tested the exercise again and again, it seem not always work on emulator! Sometimes ok, sometimes not ok as your case! But work on true Nexus One running 2.2.1. So I think it's problem of emulator.

    ReplyDelete
  9. this example gives the same address every time because you set the LATITUDE & LONGITUDE on the java file..?.if you change location will still show the same address?
    if i want to have the address i am without giving the LAT LONG what should i do?

    ReplyDelete
  10. hello dimitrismidas,

    Yes, the LAT & LONG are hard coded, so the returned address is always the same.

    You can implement two EditText for user to enter LAT & LONG.

    ReplyDelete
  11. it always given an Exception :
    java.io.IOException: Service Not Found

    I couldnt understand which type of service required

    ReplyDelete
  12. Geocoder is a online service.

    ReplyDelete
  13. Hi Android Er,
    Thank you very much for the nice guide.
    Being a beginner myself, I have few questions in mind.
    Could you please guide us through the requirements for the Manifest File of this application. Would be nice to know which API level you are targeting in this current project (Also Google API / Android API).

    regards

    ReplyDelete
  14. i cant enable gps in my emulator and i cant set lattitude and longitude from location control also

    ReplyDelete
  15. how can get latitude and longitude of two locations at one time for showing root of two location on goggle map in android?

    ReplyDelete
  16. i had try but it show first time it give msg like No Address returned! and second time Canont get Address! .. give me solution...

    ReplyDelete
  17. how can i get latitude and longitude of particular places

    ReplyDelete
  18. hello rajan,

    Depends on what you want to do:
    - you can use Geocoder(http://developer.android.com/reference/android/location/Geocoder.html), here (http://android-er.blogspot.com/2011/02/get-address-from-location-using.html) is my example, but it seem not available sometimes.
    - If you want implement with Google Maps Android API v2, you can get user touch on map and get the location(http://android-er.blogspot.com/2013/01/google-maps-android-api-v2-example.html).

    ReplyDelete
  19. I want to send lat long to a particular ip address... so can you give me code...???
    please i am new in android and i have tried many things but can not get any thing in right direction... please give me code to send lat long to a particular ip...

    ReplyDelete
  20. Hi,
    I Want To Get traffic status in particular Road From Source To Destination and i need to Calculate time As Well as For that how Can Implement can u please give me one idea about that how can we get how much traffic is there in that road.....

    ReplyDelete
  21. Hi, I just want to ask for a help. how to insert the latitude and longitude
    in android studio using spinner. thank you

    ReplyDelete