How to get Latitude and Longitude of the mobile device in android?

前端 未结 8 1530
隐瞒了意图╮
隐瞒了意图╮ 2020-11-22 16:09

How do I get the current Latitude and Longitude of the mobile device in android using location tools?

8条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-22 16:38

    Above solutions is also correct, but some time if location is null then it crash the app or not working properly. The best way to get Latitude and Longitude of android is:

     Geocoder geocoder;
         String bestProvider;
         List
    user = null; double lat; double lng; LocationManager lm = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE); Criteria criteria = new Criteria(); bestProvider = lm.getBestProvider(criteria, false); Location location = lm.getLastKnownLocation(bestProvider); if (location == null){ Toast.makeText(activity,"Location Not found",Toast.LENGTH_LONG).show(); }else{ geocoder = new Geocoder(activity); try { user = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1); lat=(double)user.get(0).getLatitude(); lng=(double)user.get(0).getLongitude(); System.out.println(" DDD lat: " +lat+", longitude: "+lng); }catch (Exception e) { e.printStackTrace(); } }

提交回复
热议问题