首先獲取LocationManager、Location及Criteria
- LocationManager locationManager;
- String context = Context.LOCATION_SERVICE;
- locationManager = (LocationManager) getSystemService(context);
- Criteria criteria = new Criteria();
- criteria.setAccuracy(Criteria.ACCURACY_FINE);
- criteria.setAltitudeRequired(false);
- criteria.setBearingRequired(false);
- criteria.setCostAllowed(false);
- criteria.setPowerRequirement(Criteria.POWER_LOW);
- String provider = locationManager.getBestProvider(criteria,
- true);
- Location location = locationManager
- .getLastKnownLocation(provider);
Criteria 類介紹:
Criteria是“精確度”的意思,Criteria類提供若干個查詢條件:
(1) public void setAccuracy( int accuracy)
位置解析的精度,高或低
參數: Criteria. ACCURACY_FINE,
精確模式;
Criteria. ACCURACY_COARSE,模糊模式;
(2) public void setAltitudeRequired(booleanaltitudeRequired)
是否提供海拔高度信息,是或否
(3) public void setBearingRequired(boolean bearingRequired)
是否提供方向信息,是或否
(4) public void setCostAllowed(boolean costAllowed)
是否允許運營商計費,是或否
(5) public void setPowerRequirement(int level)
電池消耗,無、低、中、高,參數 Criteria. NO_REQUIREMENT,Criteria. POWER_LOW,Criteria. POWER_MEDIUM, orCriteria. POWER_HIGH,
(6) public void setSpeedRequired(boolean speedRequired)
是否提供速度信息,是或否
獲取地理信息函數:
- private void updateWithNewLocation(Location location) {
- String coordinate;
- TextView loc = (TextView) findViewById(R.id.loc);
- String addressStr = "no address \n";
-
- if (location != null) {
- double lat = location.getLatitude();
- double lng = location.getLongitude();
- coordinate = "Latitude:" + lat + "\nLongitude:" + lng;
- double latitude = location.getLatitude();
- double longitude = location.getLongitude();
- Geocoder geocoder = new Geocoder(context, Locale.getDefault());
- try {
- List<Address> addresses = geocoder.getFromLocation(latitude,
- longitude, 1);
- StringBuilder sb = new StringBuilder();
- if (addresses.size() > 0) {
- Address address = addresses.get(0);
- for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
- sb.append(address.getAddressLine(i)).append("\n");
- }
- sb.append(address.getLocality()).append("\n");
- sb.append(address.getLocality()).append("\n");
- sb.append(address.getCountryName());
- addressStr = sb.toString();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- } else {
- coordinate = "no coordinate!\n";
- }
- loc.setText("your coordinate:\n" + coordinate + "\n"
- + addressStr);
- }