andbook!.pdf - Learning Android Get an anddev.org - Android-Shirt Back to index
anddev.org Header Logo
FAQ Search Top rated articles Browse Feeds anddev.org - Authors Contact Details Register Log in

Simple GoogleMaps (GeoCoder / Convert address to lon/lat)


 
       anddev.org - Android Development Community | Android Tutorials | Index -> Map Tutorials
Author Message
michels
Junior Developer
Junior Developer


Joined: 24 Sep 2008
Posts: 17
Location: Germany

PostPosted: Wed Sep 24, 2008 4:15 pm    Post subject: Simple GoogleMaps (GeoCoder / Convert address to lon/lat) Reply with quote

GoogleMaps with Geocoder Class


This tutorial is also available in german at my android weblog Androidianer.de

Hey there,

I've written this tutorial, because there were a lot of questions in the android-group and in this forum about the functionality of the Geocoder Class and the possibility to convert an address in the longitude and latitude.
I hope this tutorial can clarify the most problems.

What the application can do:
Convert an entered address in longitude and latitude and display it in a map.

How it looks like:


Here we go:

1. Create a nice layout in the main.xml. I will not explain XML-layouting here, cause there are a lot of good tutorials from plusminus in this forum. Donwload the attached source code to see my main.xml

2. Add the following permissions to the Manifest.xml over the <application> Tag

XML:

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />


3. Have fun with java. It's so easy with GeoCoder class:

All you have to do is:
- Create a new Geocoder instance
Java:

gc = new Geocoder(this); //create new geocoder instance


- Write a OnClickListener for the search button (btnSearch) and get the entered address from the EditText-field (address)
Java:

gc = new Geocoder(this); //create new geocoder instance
btnSearch.setOnClickListener(new OnClickListener() {
  public void onClick(View v) {
    String addressInput = adress.getText().toString(); //Get input text
  }
});


- Let the GeoCoder class search for the entered address (don't forget the try-catch-statement)
Java:

gc = new Geocoder(this); //create new geocoder instance
btnSearch.setOnClickListener(new OnClickListener() {
  public void onClick(View v) {
    String addressInput = adress.getText().toString(); //Get input text   
    try {
      List<Address> foundAdresses = gc.getFromLocationName(addressInput, 5); //Search addresses
    }
    catch (Exception e) {
      //@todo: Show error message
    }
  }
});


- Get the longitude and latitude from the found addresses and display the map (see full source code for the navigateToLocation function)
Java:

gc = new Geocoder(this); //create new geocoder instance
btnSearch.setOnClickListener(new OnClickListener() {
  public void onClick(View v) {
    String addressInput = adress.getText().toString(); //Get input text   
    try {
      List<Address> foundAdresses = gc.getFromLocationName(addressInput, 5); //Search addresses
      for (int i = 0; i < foundAdresses.size(); ++i) {
        //Save results as Longitude and Latitude
        //@todo: if more than one result, then show a select-list
        Address x = foundAdresses.get(i);
        lat = x.getLatitude();
        lon = x.getLongitude();
      }
      navigateToLocation((lat * 1000000), (lon * 1000000), myMap); //display the found address
    }
    catch (Exception e) {
      //@todo: Show error message
    }
  }
});



Full Source
The full source also displays an error if the address wasn't found (check also the attachment for manifest and main.xml):

Java:

//Lot's of imports here... see full source

public class simpleGoogleMaps extends MapActivity {
  protected boolean isRouteDisplayed() { return false; }
  private MapView myMap;
  private Button btnSearch;
  private EditText adress;
  private Geocoder gc;
  private double lat;
  private double lon;
     
     
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
       
    myMap = (MapView) findViewById(R.id.simpleGM_map); //Get map from XML
    btnSearch = (Button) findViewById(R.id.simpleGM_btn_search); //Get button from XML
    adress = (EditText) findViewById(R.id.simpleGM_adress); //Get address from XML
       
    gc = new Geocoder(this); //create new geocoder instance
          
    btnSearch.setOnClickListener(new OnClickListener() {
      public void onClick(View v) {
        String addressInput = adress.getText().toString(); //Get input text
                    
        try {
                         
          List<Address> foundAdresses = gc.getFromLocationName(addressInput, 5); //Search addresses
                         
          if (foundAdresses.size() == 0) { //if no address found, display an error
            Dialog locationError = new AlertDialog.Builder(simpleGoogleMaps.this)
              .setIcon(0)
              .setTitle("Error")
              .setPositiveButton(R.string.ok, null)
              .setMessage("Sorry, your address doesn't exist.")
              .create();
            locationError.show();
          }
          else { //else display address on map
            for (int i = 0; i < foundAdresses.size(); ++i) {
              //Save results as Longitude and Latitude
              //@todo: if more than one result, then show a select-list
              Address x = foundAdresses.get(i);
              lat = x.getLatitude();
              lon = x.getLongitude();
            }
          navigateToLocation((lat * 1000000), (lon * 1000000), myMap); //display the found address
          }
        }
        catch (Exception e) {
          //@todo: Show error message
        }
                    
      }
    });
    }
   
  /**
  * Navigates a given MapView to the specified Longitude and Latitude
  */

  public static void navigateToLocation (double latitude, double longitude, MapView mv) {
    GeoPoint p = new GeoPoint((int) latitude, (int) longitude); //new GeoPoint
    mv.displayZoomControls(true); //display Zoom (seems that it doesn't work yet)
    MapController mc = mv.getController();
    mc.animateTo(p); //move map to the given point
    int zoomlevel = mv.getMaxZoomLevel(); //detect maximum zoom level
    mc.setZoom(zoomlevel - 1); //zoom
    mv.setSatellite(false); //display only "normal" mapview 
  }
}


I hope this demonstrates how easy it is to convert an address in long/lat with GeoCoder.
See the GoogleMaps Mini Tutorial from lordhong if you want to add more features to your application.
But with GeoCoder you mustn't use strange Yahoo-API requests Smile

Thanks to plusminus for his great tutorials. Hope I can give something back with this one.

[Edit:] When you read the APIs you will see that it is recommended to put the getFromLocation() method in an own thread. Read the Simple GoogleMaps with Threads tutorial to see how it works.

Greetings from Germany
Mic



simpleGoogleMaps.tar
 Description:
Full Source Code

Download
 Filename:  simpleGoogleMaps.tar
 Filesize:  65.5 KB
 Downloaded:  651 Time(s)



Last edited by michels on Fri Dec 05, 2008 1:22 am; edited 3 times in total
Back to top
View user's profile Send private message
plusminus
Site Admin
Site Admin


Joined: 14 Nov 2007
Posts: 2655
Location: College Park, MD

PostPosted: Wed Sep 24, 2008 4:22 pm    Post subject: Reply with quote

Hey michels,

thank you for contributing to the community and greetings back to Germany (I'm German too).
Nice step-by-step example Exclamation
-
Best Regards,
plusminus

_________________
Download my apps Idea
Please remember, that this board is give & take Smile


| Android Development Community / Tutorials
Back to top
View user's profile Send private message Send e-mail Visit poster's website
plusminus
Site Admin
Site Admin


Joined: 14 Nov 2007
Posts: 2655
Location: College Park, MD

PostPosted: Wed Sep 24, 2008 6:07 pm    Post subject: Reply with quote

Btw, as the GeoCoder does a blocking network-query, it should be placed in a Thread, as otherwise the UI will be unavailable until it returns Exclamation
_________________
Download my apps Idea
Please remember, that this board is give & take Smile


| Android Development Community / Tutorials
Back to top
View user's profile Send private message Send e-mail Visit poster's website
michels
Junior Developer
Junior Developer


Joined: 24 Sep 2008
Posts: 17
Location: Germany

PostPosted: Thu Sep 25, 2008 1:21 pm    Post subject: Reply with quote

plusminus wrote:
Btw, as the GeoCoder does a blocking network-query, it should be placed in a Thread, as otherwise the UI will be unavailable until it returns Exclamation


Hey plusminus,

you're right. I read that too, but I'm not an expert in threads so far Wink and I thought it's too complicated to explain GeoCoder and threads in one tutorial.

So I wrote a seperate tutorial for threads last night.

Simple GoogleMaps with threads

Hope that I understand everything right.

greetings
Mic
Back to top
View user's profile Send private message
plusminus
Site Admin
Site Admin


Joined: 14 Nov 2007
Posts: 2655
Location: College Park, MD

PostPosted: Thu Sep 25, 2008 2:25 pm    Post subject: Reply with quote

Yeah thats fine. See my comment over there.

I usually do such thing with
Java:
runOnUiThread(new Runnable(){
    public void run(){
        // ...
    }
}

because then I don't have to create a new Handler, create message, handle with what-ids and stuff. So its a bit simpler.

Regards,
plusminus

_________________
Download my apps Idea
Please remember, that this board is give & take Smile


| Android Development Community / Tutorials
Back to top
View user's profile Send private message Send e-mail Visit poster's website
ndroid
Junior Developer
Junior Developer


Joined: 15 Dec 2008
Posts: 15

PostPosted: Wed Dec 17, 2008 12:48 pm    Post subject: Reply with quote

hi
i am getting following exception
" Unable to parse response from server" when i search for London.
here is the snippet
try
{
foundAdresses = gc.getFromLocationName(addressInput, 5); // Search
// addresses
Thread.sleep(1500);
}
catch (Exception e)
{
// @todo: Show error message
Log.i("TEST", "exception in thread " + e.getMessage());
}
even as i observe after first search its sending this exception evry time for any location.
Back to top
View user's profile Send private message
Display posts from previous:   
       anddev.org - Android Development Community | Android Tutorials | Index -> Map Tutorials All times are GMT + 1 Hour
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
You cannot attach files in this forum
You can download files in this forum


© 2007, Android Development Community
All rights reserved.
Powered by phpBB.