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

Posted

技术标签:

【中文标题】如何在android中使用纬度和经度获取城市名称【英文标题】:how to get city name using latitude and longitude in android 【发布时间】:2017-10-07 07:23:31 【问题描述】:

我正在尝试使用纬度和经度在 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)

【问题讨论】:

查看以下链接,您可以在线获取完整地址:Get complete address from lat and long 您的问题有很多解决方案。你可以挖谷歌。 为什么要投反对票,你应该发表评论。 @AseshaGeorge 你在说谁?? 投反对票的人 【参考方案1】:

试试

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();

【讨论】:

要求使用try catch 请分享经纬度值 我明白了,我刚刚将 1,1 更改为纬度和经度 我不知道为什么有人拒绝对我的问题投票【参考方案2】:

使用以下代码获取城市名称

 Geocoder geocoder = new Geocoder(this);

    try 
        List<Address>addresses = geocoder.getFromLocation(latitude,longitue,1);
        if (geocoder.isPresent()) 
            StringBuilder stringBuilder = new StringBuilder();
            if (addresses.size()>0) 
                Address returnAddress = addresses.get(0);

                String localityString = returnAddress.getLocality();
                String name = returnAddress.getFeatureName();
                String subLocality = returnAddress.getSubLocality();
                String country = returnAddress.getCountryName();
                String region_code = returnAddress.getCountryCode();
                String zipcode = returnAddress.getPostalCode();
                String state = returnAddress.getAdminArea();

            
         else 

        
     catch (IOException e) 
        e.printStackTrace();
    

【讨论】:

【参考方案3】:

试试这个代码,希望对你有帮助..

private static String getRegionName(double lati, double longi) 
    String regioName = "";
    Geocoder gcd = new Geocoder(AppInstance, Locale.getDefault());
    try 
        List<Address> addresses = gcd.getFromLocation(lati, longi, 1);
        if (addresses.size() > 0) 
            regioName = addresses.get(0).getLocality();
        
     catch (Exception e) 
        e.printStackTrace();
    
    return regioName;

【讨论】:

【参考方案4】:

尝试使用以下代码获取完整地址,

//Get address from Google api
        //Log.e("Else","else");
        try 
            JSONObject jsonObj = getJSONfromURL("http://maps.googleapis.com/maps/api/geocode/json?latlng=" + latitude + ","
                    + longitude + "&sensor=true");
            String Status = jsonObj.getString("status");
            if (Status.equalsIgnoreCase("OK")) 
                JSONArray Results = jsonObj.getJSONArray("results");
                JSONObject location = Results.getJSONObject(0);
                finalAddress = location.getString("formatted_address");
            
         catch (Exception e) 
            e.printStackTrace();
        

而不是,

geocoder.getFromLocation(latitude, longitude, 1);

【讨论】:

【参考方案5】:

对于避免 ArrayIndexOutOfBound,您可以添加如下 if 条件:

if (addresses != null && addresses.size() > 0) 
    String locality = addresses.get(0).getLocality();

但是,当我看到您的代码时,您正在尝试使用 GeoCoder 按钮单击来获取地址,因此请避免这种情况,因为它是网络调用。您不应该在主线程中执行网络调用,它可能会阻塞 UI 或导致 ANR。您应该使用 AsyncTask/Thread 进行网络操作,以避免 UI 阻塞。

还要确保你已经添加了

INTERNET_PERMISSION

在您的清单文件中。

希望对你有帮助!

【讨论】:

【参考方案6】:

错误表明 Array 列表为空,因此请确保初始化列表并检查它是否包含任何数据。

试试这个代码:

List<Address> addresses = new List<Address>;

addresses = geocoder.getFromLocation(latitude, longitude, 1);

【讨论】:

【参考方案7】:
if(addresses != null) 
String address = addresses.get(0).getAddressLine(0);
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();

这应该为您提供所需的信息。

【讨论】:

【参考方案8】:

从 Location 对象获取的 latlong 坐标中获取位置地址。

@Override
    public void onLocationChanged(Location location) 
        
        String longitude = "Longitude: " + location.getLongitude();
        Log.v(TAG, longitude);

        String latitude = "Latitude: " + location.getLatitude();
        Log.v(TAG, latitude);
        
        String address = null;
        String knownName = null;
        String city = null;
        String state = null;
        String country = null;
        String postalCode = null;

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

        try 
            addresses = gcd.getFromLocation(location.getLatitude(), location.getLongitude(), 1);

            address = addresses.get(0).getAddressLine(0);
            if (addresses.get(0).getFeatureName() != address) 
                knownName = addresses.get(0).getFeatureName();
            
            city = addresses.get(0).getLocality();
            state = addresses.get(0).getAdminArea();
            country = addresses.get(0).getCountryName();
            postalCode = addresses.get(0).getPostalCode();

         catch (IOException e) 
            e.printStackTrace();
        

        String foundAddress = knownName + ", " + address + ", " + city + ", " + state + ", " + country + "- " + postalCode + "\n";

        myLocation.setText(foundAddress);
        storeLocation();

    

【讨论】:

以上是关于如何在android中使用纬度和经度获取城市名称的主要内容,如果未能解决你的问题,请参考以下文章

如何使用纬度和经度获取位置名称或城市?

Laravel:如何从城市名称中获取纬度和经度点? [关闭]

从城市名称获取纬度和经度

如何从给定的纬度和经度中查找位置名称?

Gps android - 获取纬度和经度

如何使用地址和纬度/经度获取世界上所有的公园