从Longtitude和Latitude获取位置返回null

时间:2018-01-24 08:51:19

标签: android geolocation

问题导致: 地理编码需要与Google Api的连接。 在Genymotion上我没有安装'Gapps'。

解决方案例如在Genymotion上安装Gapps

我不想从longtitudelatitude获取位置信息。在我的其他应用程序中,此功能运行良好但在我的其他项目中它根本不起作用。

它需要谷歌json文件吗?关键?什么?

我还没有找到解决方案。我真的不知道为什么它每次都返回null。 我尝试了几个地方。

private String getLocationFromLongLati(String longi, String lati) throws IOException {
        if (ActivityCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 1001);
        } else {
            Geocoder geocoder = new Geocoder(MainActivity.this, Locale.GERMAN);
            List<Address> nm = geocoder.getFromLocation(Double.valueOf(lati), Double.valueOf(longi), 1);
            if(nm != null && nm.size()>0) {
                return nm.get(0).getPostalCode() + ", " + nm.get(0).getLocality();
            }
        }
        return null;

    }

4 个答案:

答案 0 :(得分:0)

您可以尝试使用此方法通过其LatLng获取位置详细信息(名称)。这对我来说可以。只需在Geocoder构造函数中将您的类名从MainActivity更改为您的。

private String getAddressFromLatLng(LatLng latLng) {
    Geocoder geocoder = new Geocoder(MainActivity.this);

    String address = "";
    try {
        address = geocoder
                .getFromLocation(latLng.latitude, latLng.longitude, 1)
                .get(0).getAddressLine(0);
    } catch (IOException e) {
    }
    return address;
}

您可以在需要LatLng地址的活动中的任何位置使用此方法。

希望这会对你有所帮助。

答案 1 :(得分:0)

Geocoder并不总是返回一个值。您可以尝试在for循环中发送3次请求。我应该能够至少返回一次。如果没有,那么它们可能是连接问题,或者可能是其他问题,例如服务器拒绝回复您的请求。试着看看这些主题:

Geocoder doesn't always return a valuegeocoder.getFromLocationName returns only null

我每次使用这种更可靠的方式来获取地址:

JSONObject ret = getLocationInfo(); 
JSONObject location;
String location_string;
try {
     location = ret.getJSONArray("results").getJSONObject(0);
     location_string = location.getString("formatted_address");
     Log.d("test", "formattted address:" + location_string);
} catch (JSONException e1) {
     e1.printStackTrace();
}


public JSONObject getLocationInfo() {

    HttpGet httpGet = new HttpGet("http://maps.google.com/maps/api/geocode/json?latlng="+lat+","+lng+"&sensor=true");
    HttpClient client = new DefaultHttpClient();
    HttpResponse response;
    StringBuilder stringBuilder = new StringBuilder();

    try {
        response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();
        InputStream stream = entity.getContent();
        int b;
        while ((b = stream.read()) != -1) {
            stringBuilder.append((char) b);
        }
    } catch (ClientProtocolException e) {
        } catch (IOException e) {
    }

    JSONObject jsonObject = new JSONObject();
    try {
        jsonObject = new JSONObject(stringBuilder.toString());
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return jsonObject;
}

答案 2 :(得分:0)

你可以尝试!

public static Address getAddress(LatLng latLng) {
            if(latLng != null){
                Geocoder geocoder;
                List<Address> addresses;
                geocoder = new Geocoder(context, Locale.getDefault());

                try {
                    addresses = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
                    return addresses.get(0);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }



    public static String getInfoAddress(Address address) {
                if (address != null) {
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i <= address.getMaxAddressLineIndex(); i++) {
                        sb.append(address.getAddressLine(i)).append(", ");
                    }
                    return sb.toString();
                }
                return StringUtils.EMPTY;
            }

答案 3 :(得分:0)

在gradle文件中添加此库

implementation 'com.google.android.gms:play-services-location:11.8.0'

在清单文件中添加权限

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

这是代码

private FusedLocationProviderClient mFusedLocationClient;
private void getCurrentLatLong() {
    //get Current Location
    mFusedLocationClient = LocationServices.getFusedLocationProviderClient(mContext);
    if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }


    mFusedLocationClient.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
        @Override
        public void onSuccess(Location location) {
            if (location != null) {

                Log.e("location", location.getLatitude() + "----" + location.getLongitude() + "----" + location.getSpeed());
            } else
                Toast.makeText(mContext, "Get Current Location not found", Toast.LENGTH_SHORT).show();
        }
    });
}