Convert Location To Address - Android Map

Android examples for Map:Address

Description

Convert Location To Address

Demo Code


//package com.java2s;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.content.Context;
import android.location.Address;

import android.location.Geocoder;
import android.location.Location;

public class Main {
    public static String ConvertLocationToAddress(Context context,
            Location location) {//from  w w w  .  j ava2s . co  m
        int timeout = 10;
        StringBuffer address = new StringBuffer();
        Geocoder geoCoder = new Geocoder(context, Locale.getDefault());
        try {
            List<Address> addresses = geoCoder.getFromLocation(
                    location.getLatitude(), location.getLongitude(), 10);

            int loop = 0;
            while (loop < timeout) {
                addresses = geoCoder
                        .getFromLocation(location.getLatitude(),
                                location.getLongitude(), 10);
                loop++;
                if (addresses.size() > 0) {
                    break;
                }
            }

            if (addresses.size() > 0) {
                int maxLoop = addresses.get(0).getMaxAddressLineIndex();
                for (int index = 0; index < maxLoop; index++) {
                    address.append(addresses.get(0).getAddressLine(index));
                    if (index != maxLoop - 1) {
                        address.append(" ");
                    }
                }
                if (addresses.get(0).getCountryName() != null) {
                    address.append(", ");
                    address.append(addresses.get(0).getCountryName());
                }
            }
        } catch (IOException e) {
            return "NearBy";

        }

        return address.toString();
    }
}

Related Tutorials