欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Android 得到地理位置并分析出具体城市

程序员文章站 2022-07-14 16:04:51
...
/**
	 * 通过GPS得到城市名
	 * 
	 * @param context
	 *            一個Activity
	 * @return 城市名
	 */
	public static String getCityName(Context context) {
		LocationManager locationManager;
		String contextString = Context.LOCATION_SERVICE;
		locationManager = (LocationManager) context.getSystemService(contextString);
		Criteria criteria = new Criteria();
		criteria.setAccuracy(Criteria.ACCURACY_FINE);
		criteria.setAltitudeRequired(false);
		criteria.setBearingRequired(false);
		criteria.setCostAllowed(false);
		criteria.setPowerRequirement(Criteria.POWER_LOW);
		String cityName = null;
		// 取得效果最好的criteria
		String provider = locationManager.getBestProvider(criteria, true);
		if (provider == null) {
			return null;
		}
		// 得到坐标相关的信息
		Location location = locationManager.getLastKnownLocation(provider);
		if (location == null) {
			return null;
		}

		if (location != null) {
			double latitude = location.getLatitude();
			double longitude = location.getLongitude();
			// 更具地理环境来确定编码
			Geocoder gc = new Geocoder(context, Locale.getDefault());
			try {
				// 取得地址相关的一些信息\经度、纬度
				List<Address> addresses = gc.getFromLocation(latitude, longitude, 1);
				StringBuilder sb = new StringBuilder();
				if (addresses.size() > 0) {
					Address address = addresses.get(0);
					sb.append(address.getLocality()).append("\n");
					cityName = sb.toString();
				}
			} catch (IOException e) {
			}
		}
		return cityName;
	}
相关标签: gps