为什么在android studio中,我当前位置的城市为空?

问题描述 投票:0回答:1

嗨,我做了一个简单的应用程序,获取当前位置的GPS,并显示当前城市,但当我运行它,它显示经纬度正确,但返回城市为空。

Location mLastLocation = locationResult.getLastLocation();
lat = mLastLocation.getLatitude() + "";
lon = mLastLocation.getLongitude() + "";
Geocoder gcd = new Geocoder(MLocationListener.this, Locale.getDefault());

List<Address> addresses;
try {
    addresses = gcd.getFromLocation(mLastLocation.getLatitude(), mLastLocation.getLongitude(), 1);
    if (addresses.size() > 0) {
        // Log.d("city", addresses.get(0).getLocality());
        String cityName = addresses.get(0).getLocality();
        //Toast.makeText(MLocationListener.this, cityName, Toast.LENGTH_SHORT).show();
    }
} catch (IOException e) {
    e.printStackTrace();
}
java android location
1个回答
0
投票

试试这个解决方案。

Google map = googleMap;
this.map = googleMap;
this.map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
this.map.getUiSettings().setZoomControlsEnabled(true);
this.map.getUiSettings().setCompassEnabled(true);
this.map.getUiSettings().setMyLocationButtonEnabled(true);
this.map.getUiSettings().setZoomGesturesEnabled(true);
this.map.getUiSettings().setRotateGesturesEnabled(true);
String s = "New York"; 
List<Address> addressList = null;
if(s!=null){ 
    Geocoder geocoder = new Geocoder( ); //inside put "getActivity()" or "this"
    try{
        addressList=geocoder.getFromLocationName(s, 1);
    }catch(IOException e){
        e.printStackTrace();
    }
    Address address = addressList.get(0);
    LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
    map.addMarker(new MarkerOptions().position(latLng).title(s));
    map.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 10));
}

把这种类型的解决方案放在一个实现了... OnMapReadyCallback的方法中,在 OnMapReady(GoogleMap googleMap)

希望能帮到你

© www.soinside.com 2019 - 2024. All rights reserved.