如何从经度和经度获取街道地址

时间:2015-06-16 09:09:19

标签: android google-maps

我正在编写一个从谷歌地图获取完整位置的程序,我设法获得经度和经度,但是当谈到地址时,我做了所有在不同网站中提到的但我得到一个空列表。

以下是代码:

这是将地址保存在列表中的功能

public List<Address> getAddress() {
    try {
        Geocoder geocoder;
        List<Address> addresses;
        double latitude, longitude;
        latitude = Double.parseDouble(lat);
        longitude =  Double.parseDouble(lng);
        System.out.println(latitude + " / " + longitude);
        geocoder = new Geocoder(this);
        if (latitude != 0 || longitude != 0) {
            addresses = geocoder.getFromLocation(latitude ,
                    longitude, 2);
            return addresses;
        } else {
            Toast.makeText(this, "latitude and longitude are null",
                    Toast.LENGTH_LONG).show();
            return null;
        }
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

这是调用它的函数:

@Override
public void onLocationChanged(Location location) {

    lng = location.getLongitude() + "";
    lat = location.getLatitude() + "";

    try
    {
        getAddress();
    }
    catch (Exception e)
    {
        System.out.println("Can't Call getAddress()");
    }

    gotoLocation(location);

}

每次调用onLocationChanged()时,这都是给定的错误

  

06-16 12:06:23.595:W / System.err(28123):java.lang.IndexOutOfBoundsException:索引0无效,大小为0   06-16 12:06:23.595:W / System.err(28123):at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)   06-16 12:06:23.595:W / System.err(28123):at java.util.ArrayList.get(ArrayList.java:308)   06-16 12:06:23.595:W / System.err(28123):at com.MOS.fastfood.MapActivity.getAddress(MapActivity.java:559)   06-16 12:06:23.595:W / System.err(28123):at com.MOS.fastfood.MapActivity.onLocationChanged(MapActivity.java:522)   06-16 12:06:23.595:W / System.err(28123):at com.google.android.gms.internal.zzpe $ zza.handleMessage(Unknown Source)   06-16 12:06:23.595:W / System.err(28123):在android.os.Handler.dispatchMessage(Handler.java:99)   06-16 12:06:23.600:W / System.err(28123):在android.os.Looper.loop(Looper.java:176)   06-16 12:06:23.600:W / System.err(28123):在android.app.ActivityThread.main(ActivityThread.java:5419)   06-16 12:06:23.600:W / System.err(28123):at java.lang.reflect.Method.invokeNative(Native Method)   06-16 12:06:23.600:W / System.err(28123):at java.lang.reflect.Method.invoke(Method.java:525)   06-16 12:06:23.600:W / System.err(28123):at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:1046)   06-16 12:06:23.600:W / System.err(28123):at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)   06-16 12:06:23.600:W / System.err(28123):at dalvik.system.NativeStart.main(Native Method)

这是清单

    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.MOS.fastfood"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="11"
    android:targetSdkVersion="22" />

<!-- added permission manually to reveice MAP -->
<permission
    android:name="com.MOS.fastfood.permission.MAPS_RECEIVE"
    android:protectionLevel="signature" >
</permission>

<!-- permissions to access internet -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>

<!-- important permissions to fetch map from google -->
<uses-permission android:name="com.MOS.fastfood.permission.MAPS_RECEIVE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />

<!-- only devices that support version 2.0 of openGL can download, for graphics -->
<uses-feature
    android:glEsVersion="0x00020000"
    android:required="true" />

<!-- two permissions used to determine the current location using network towers and gps -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <!-- ADDING THE DEBUGGING KEY -->
    <meta-data
        android:name="com.google.android.maps.v2.API_KEY"
        android:value="***" />

    <!-- THIS META DATA ALLOWS "ISGOOGLEPLAYSERVICES ENABLED" TO FUNCTION WITHOUT CRASH -->
    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />

    <activity
        android:name=".AddRestaurantActivity"
        android:label="@string/title_activity_add_restaurant" >
    </activity>
    <activity
        android:name=".FacebookLoginActivity"
        android:label="@string/title_activity_facebook_login" >
    </activity>
    <activity
        android:name=".ListActivity"
        android:label="@string/title_activity_list" >
    </activity>
    <activity
        android:name=".MapActivity"
        android:label="@string/title_activity_map" >
    </activity>
    <activity
        android:name=".RestaurantInfoActivity"
        android:label="@string/title_activity_rate" >
    </activity>
    <activity
        android:name=".Loader"
        android:label="@string/title_activity_loader" >
    </activity>
</application>

</manifest>

2 个答案:

答案 0 :(得分:1)

试试此代码

 Geocoder geocoder;
 List<Address> addresses;
 geocoder = new Geocoder(this, Locale.getDefault());

 addresses = geocoder.getFromLocation(latitude, longitude, 1); // Here 1     represent max location result to returned, by documents it recommended 1 to 5
 String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()

String city = addresses.get(0).getLocality();
String state = addresses.get(0).getAdminArea();
String country = addresses.get(0).getCountryName();
String postalCode = addresses.get(0).getPostalCode();
String knownName = addresses.get(0).getFeatureName();

答案 1 :(得分:0)

这是为我工作的课程。

public class SubscriberDetails extends Activity implements GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener,OnEditorActionListener{

    private String finalAddress = "";

    //GPS 
    private boolean statusOfGPS = false;

    //GPS listener
    public static   Double _latitudeValue = null;
    public static   Double _longitudeValue = null;

    GPSTracker gps;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.subscriber_detail);


        gps = new GPSTracker(this);

        _latitudeValue = gps.getLatitude();
        _longitudeValue = gps.getLongitude();


        (new GetAddressTask(this)).execute();

    }



    /*
     * Following is a subclass of AsyncTask which has been used to get
     * address corresponding to the given latitude & longitude.
     */
    private class GetAddressTask extends AsyncTask<Location, Void, String>{
        Context mContext;
        public GetAddressTask(Context context) {
            super();
            mContext = context;
        }

        /*
         * When the task finishes, onPostExecute() displays the address. 
         */
        @Override
        protected void onPostExecute(String address) {

        }
        @Override
        protected String doInBackground(Location... params) {

            try {
                //current location
                Geocoder geoCoder = new Geocoder(SubscriberDetails.this, Locale.getDefault());
                StringBuilder builder = new StringBuilder();

                List<Address> address = geoCoder.getFromLocation(_latitudeValue,
                        _longitudeValue, 1);
                int maxLines = address.get(0).getMaxAddressLineIndex();
                for (int i=0; i<maxLines; i++) {
                    String addressStr = address.get(0).getAddressLine(i);
                    builder.append(addressStr);
                    builder.append(" ");
                }

                finalAddress = builder.toString(); //This is the complete address.
                System.out.println("Address = " +finalAddress);
            } catch (IOException e) {

            }
            catch (NullPointerException e) {

            }

            System.out.println("Current Locations = " + finalAddress);
            return finalAddress;


        }
    }// AsyncTask class



    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        // Display the error code on failure

        System.out.println("Connection Failure : " + connectionResult.getErrorCode());
    }

    @Override
    public void onConnected(Bundle arg0) {

        System.out.println("Connected");
    }

    @Override
    public void onDisconnected() {
        System.out.println("Disconnected. Please re-connect.");
    }

}

和GPSTracker类:​​

public class GPSTracker extends Service implements LocationListener {

    private final Context mContext;

    // flag for GPS status
    boolean isGPSEnabled = false;

    // flag for network status
    boolean isNetworkEnabled = false;

    // flag for GPS status
    boolean canGetLocation = false;

    //flag for WIFi
    boolean isWifiEnabled = false;

    Location location; // location
    double latitude; // latitude
    double longitude; // longitude

    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

    // Declaring a Location Manager
    protected LocationManager locationManager;

    public GPSTracker(Context context) {
        this.mContext = context;
        getLocation();
    }

    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);

            // getting GPS status
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);

            // getting network status
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            isWifiEnabled = locationManager.isProviderEnabled(LocationManager.PASSIVE_PROVIDER);


            if (!isGPSEnabled && !isNetworkEnabled&&!isWifiEnabled) {
                // no network provider is enabled
            } else {
                this.canGetLocation = true;
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                            SubscriberDetails._latitudeValue = latitude;
                            SubscriberDetails._longitudeValue = longitude;

                        }
                    }
                }
                // if GPS Enabled get lat/long using GPS Services
                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                                SubscriberDetails._latitudeValue = latitude;
                                SubscriberDetails._longitudeValue = longitude;

                            }
                        }
                    }
                } 
                if (isWifiEnabled) {

                    if (location == null) {
                        locationManager.requestLocationUpdates(
                                LocationManager.PASSIVE_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                                SubscriberDetails._latitudeValue = latitude;
                                SubscriberDetails._longitudeValue = longitude;
                            }
                        }
                    }

                }
            }

        } catch (Exception e) {
        }
        return location;
    }

    /**
     * Stop using GPS listener Calling this function will stop using GPS in your
     * app.
     * */
    public void stopUsingGPS() {
        if (locationManager != null) {
            locationManager.removeUpdates(GPSTracker.this);
        }
    }

    /**
     * Function to get latitude
     * */
    public double getLatitude() {
        if (location != null) {
            latitude = location.getLatitude();
        }
        // return latitude
        return latitude;
    }

    /**
     * Function to get longitude
     * */
    public double getLongitude() {
        if (location != null) {
            longitude = location.getLongitude();
        }

        // return longitude
        return longitude;
    }

    /**
     * Function to check GPS/wifi enabled
     * 
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }

    /**
     * Function to show settings alert dialog On pressing Settings button will
     * lauch Settings Options
     * */
    public void showSettingsAlert() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        // Setting DialogHelp Title
        alertDialog.setTitle("GPS is settings");

        // Setting DialogHelp Message
        alertDialog
                .setMessage("GPS is not enabled. Do you want to go to settings menu?");

        // On pressing Settings button
        alertDialog.setPositiveButton("Settings",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(
                                Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        mContext.startActivity(intent);
                    }
                });

        // on pressing cancel button
        alertDialog.setNegativeButton("Cancel",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });

        // Showing Alert Message
        alertDialog.show();
    }

    @Override
    public void onLocationChanged(Location location) {
        float bestAccuracy = -1f;
        if (location.getAccuracy() != 0.0f
            && (location.getAccuracy() < bestAccuracy) || bestAccuracy == -1f) {
                locationManager.removeUpdates(this);
        }
        bestAccuracy = location.getAccuracy();
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    public float getAccurecy()
    {
        return location.getAccuracy();
    }

}