android - 如何在android中使用纬度和经度获取城市名称

标签 android google-maps indexoutofboundsexception reverse-geocoding

我正在尝试使用纬度和经度在 TextView 中获取城市。我收到 IndexOutOfBoundsException

AndroidGPSTrackingActivity.java

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

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

import static com.example.khaledsb.location.R.id.lng;
import static java.util.Locale.*;

public class AndroidGPSTrackingActivity extends Activity {

    public static float distFrom(float lat1, float lng1, float lat2, float lng2) {
        double earthRadius = 6371000; //meters
        double dLat = Math.toRadians(lat2-lat1);
        double dLng = Math.toRadians(lng2-lng1);
        double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
                Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
                        Math.sin(dLng/2) * Math.sin(dLng/2);
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
        float dist = (float) (earthRadius * c);

        return dist;
    }

    Button btnShowLocation;

    // GPSTracker class
    GPSTracker gps;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        btnShowLocation = (Button) findViewById(R.id.btnShowLocation);

          final TextView lat =(TextView) findViewById(R.id.lat);
          final TextView lon = (TextView) findViewById(R.id.longt);
          final TextView addr = (TextView) findViewById(R.id.address);

        // show location button click event
        btnShowLocation.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {        
                // create class object
                gps = new GPSTracker(AndroidGPSTrackingActivity.this);

                // check if GPS enabled     
                if(gps.canGetLocation()){

                    double latitude = gps.getLatitude();
                    double longitude = gps.getLongitude();

                    double Distance;
                    Distance = distFrom((float) 36.5925907, 2.9051544f, 36.5805505f, 2.914749f);

                    lat.setText(String.valueOf(latitude));
                    lon.setText(String.valueOf(longitude));


                    Geocoder geocoder = new Geocoder(AndroidGPSTrackingActivity.this, Locale.ENGLISH);

                    try {
                        List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);

                        if(addresses != null) {
                            Address returnedAddress = addresses.get(0);
                            StringBuilder strReturnedAddress = new StringBuilder("Address:\n");
                            for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
                                strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
                            }
                            addr.setText(strReturnedAddress.toString());
                        }
                        else{
                            addr.setText("No Address returned!");
                        }
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        addr.setText("Can not get Address!");
                    }

                    // \n is for new line
                    //Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude+" " +
                            //"  diastance "+Distance, Toast.LENGTH_LONG).show();
                }else{
                    // can't get location
                    // GPS or Network is not enabled
                    // Ask user to enable GPS/network in settings
                    gps.showSettingsAlert();
                }

            }
        });
    }

}

我在 logcat 中收到以下错误:

5-09 11:17:21.858 4501-4501/com.example.khaledsb.location E/AndroidRuntime: FATAL EXCEPTION: main
     java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
                                                                                 at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
     at java.util.ArrayList.get(ArrayList.java:304)
     at com.example.khaledsb.location.AndroidGPSTrackingActivity$1.onClick(AndroidGPSTrackingActivity.java:79)
     at android.view.View.performClick(View.java:4204)
     at android.view.View$PerformClick.run(View.java:17355)
     at android.os.Handler.handleCallback(Handler.java:725)
     at android.os.Handler.dispatchMessage(Handler.java:92)
     at android.os.Looper.loop(Looper.java:137)
     at android.app.ActivityThread.main(ActivityThread.java:5041)
     at java.lang.reflect.Method.invokeNative(Native Method)
     at java.lang.reflect.Method.invoke(Method.java:511)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
     at dalvik.system.NativeStart.main(Native Method)

最佳答案

尝试

Geocoder gcd = new Geocoder(this, Locale.getDefault());
List<Address> addresses = null;
try {
    addresses = gcd.getFromLocation(lat, lng, 1);
} catch (IOException e) {
    e.printStackTrace();
}
if (addresses != null && addresses.size() > 0) {
    String locality = addresses.get(0).getLocality();
}

关于android - 如何在android中使用纬度和经度获取城市名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43862079/

相关文章:

android - 无法加载类型 'Android.OS.BaseBundle"

android - 从 Android 设备访问本地主机 api

javascript - 谷歌地图,如何捕获POI上的右键单击事件

javascript - 如何在聚合物元素中使用来自 Dart 的 javascript

python - 通过 Pandas 中的函数替换 NaN 时索引超出范围

java - 如何按每个字符串中元音的数量对字符串数组进行升序排序?

java - SQLite 高分,CursorIndexOutOfBounds - Android

android - TelephonyManager.getPhoneType 的值是跟phone 和一个固定的常量有关还是跟sim 卡有关?

google-maps - 在 Dart 中使用 google_maps_flutter 的 GestureDetector

android - 有没有办法在导航高级示例中定义开始选项卡?