位置管理器在地理坐标中找不到城市时崩溃



我正在使用Locationmanager获取用户GeoPoints,然后将其转换为城市/州。问题是一些用户在发生这种情况时会"崩溃",当我取出地理点到城市的转换时,如下图所示,他们不会崩溃。所以我指出了这一点,我假设它根据他们的地理坐标为某些人返回 null。如果我绝对需要,有没有更可靠的方法来获得某人的城市?

public class UserLocation implements LocationListener {
        @Override
        public void onLocationChanged(Location loc) {
            if (loc != null)
            {
                mLatitude = loc.getLatitude();
                mLongitude = loc.getLongitude();
                Geocoder geoCoder = new Geocoder(getActivity(), Locale.getDefault());
                List<Address> addresses;
                try {
                    addresses = geoCoder.getFromLocation(mLatitude, mLongitude, 10);
                     int i=1;
                     for(Address addObj:addresses)
                     {
                         // Looping once
                         if(i==1)
                         { 
                             //Setting city
                             mCity = addObj.getSubLocality();                            
                             //setting state
                             mState = returnStateAbbreviation(addObj.getAdminArea());

                             i++;
                         }
                     }
                } catch (IOException e1) {
                    e1.printStackTrace();
                }}
            else
            {
                Log.i(mTag, "No location found, hrmp?");
            }
            // Stopping Location Updates
            mLocationManager.removeUpdates(mLocationListener);
        }

或者只比较 2 个地理点以显示它们之间的距离以列出而不是城市和州会更容易吗?

正如@Selvin所说,getFromLocation 可以根据文档返回 null

返回 地址对象的列表。如果未找到匹配项或没有可用的后端服务,则返回 null 或空列表

在循环访问地址之前,您需要检查它是否为 null

addresses = geoCoder.getFromLocation(mLatitude, mLongitude, 10);
if (addresses != null) {
    int i=1;
    for(Address addObj:addresses)
    {
        ...
    }
}

关于你的第二个问题,这取决于你想做什么,但计算两点之间的距离很容易。您可以使用此位置方法

public static void distanceBetween (double startLatitude, double startLongitude, double endLatitude, double endLongitude, float[] results)

最新更新