ckbln
ckbln

Reputation: 83

How to get Lat Long using Adress AND Zip Code Android

There was a question years ago, how to get lat long coordinates using only the adress ( here is the link to the question: How can I find the latitude and longitude from address? )

I understand the accepted answer there, but my problem is, for example, in Germany you have no unique adresses, so if I use only adresses to get lat and long coordinates, I may get wrong lat long coordinates. Like, there is one adress called "Hauptstrasse" which is in Berlin and in Frankfurt. So I will get wrong coordinates.

Is there any way to use Adress AND Zip code to get the right lat long coordinates ?

This code for example only uses adresses:

public GeoPoint getLocationFromAddress(String strAddress){

    Geocoder coder = new Geocoder(this);
    List<Address> address;
    GeoPoint p1 = null;

    try {
        address = coder.getFromLocationName(strAddress,5);
        if (address==null) {
           return null;
        }
        Address location=address.get(0);
        location.getLatitude();
        location.getLongitude();

        p1 = new GeoPoint((double) (location.getLatitude() * 1E6),
                          (double) (location.getLongitude() * 1E6));

        return p1;
    }
}

Upvotes: 1

Views: 523

Answers (1)

Blnpwr
Blnpwr

Reputation: 1875

I had the same problem.

This is how I solved this problem.

I have a txt file that contains adresses, zip codes and city names.

To keep your example for Germany: Hauptstrasse 123, 10978, Germany (this will be somewhere in Berlin)

Then, I put this txt file into assets folder and used a BufferedReader and created an Array.

    public void readFile(){

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(getAssets().open("YOURFILE")));
            String line;
            while ((line = reader.readLine()) != null) {

                String splittedLine [] = line.split(",");
                int numberofElements =2;
                String[] onlyAdressandZip = Arrays.copyOf(splittedLine, numberofElements);
 } catch (IOException e) {
            e.printStackTrace();
        }

As you can see, I did not use the name of the country (Germany) that's why I used Arrays.copyOf

Hauptstrasse 123, 10978 , Germany has a length of 3 but we only need Hauptstrasse 123 and 10978 that explains int numberofElements =2

That's it and then you can give onlyAdressandZip[0] and onlyAdressandZip[1] as input for the GeoCoder to get the right lat and long coordinates.

Upvotes: 1

Related Questions