在android中,如何以公里为单位获得两个经度和两个纬度之间的距离?
说明: 我知道这个问题大部分是重复的,但我有点困惑。我正在进行现场应用。其中,我读取了JSON中的JSON数据,其中有一些经度和纬度。我获取与当前经度和纬度的比较。我找到了一些方法并尝试了,但没有得到预期的结果 我想比较一下我当前的经度和纬度与json经度和纬度的距离是否在五公里以下。如果用户超出范围,如超过5公里,则会显示消息user out range(用户超出范围) 这里,是我获取经度和纬度的代码在android中,如何以公里为单位获得两个经度和两个纬度之间的距离?,android,json,Android,Json,说明: 我知道这个问题大部分是重复的,但我有点困惑。我正在进行现场应用。其中,我读取了JSON中的JSON数据,其中有一些经度和纬度。我获取与当前经度和纬度的比较。我找到了一些方法并尝试了,但没有得到预期的结果 我想比较一下我当前的经度和纬度与json经度和纬度的距离是否在五公里以下。如果用户超出范围,如超过5公里,则会显示消息user out range(用户超出范围) 这里,是我获取经度和纬度的代码 public class HomeFragment extends Fragment imp
public class HomeFragment extends Fragment implements ConnectionCallbacks, OnConnectionFailedListener,LocationListener{
public static final String TAG=TransactionFragment.class.getSimpleName();
public static final String KEY_UGC="postData[ugc]";
public static final String KEY_CUSTOMER_ID="postData[customerid]";
public static final String KEY_UGC_ID="postData[ugcid]";
View rootView;
PreferenceSetting prefManager;
ListView lvTransaction;
List<String> items;
TextView txtPoints;
Button btnUgc,btnMore;
List<Trasaction> trasactionList;
TextView lblTrasaction,lblStation,lblNoBottle,lblPointsColl,lblPoints;
int totalPoints=0;
MainActivity activity;
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private double currentLatitude;
private double currentLongitude;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
rootView=inflater.inflate(R.layout.fragment_home,container,false);
prefManager=PreferenceSetting.getInstance(getActivity());
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
// The next two lines tell the new client that “this” current class will handle connection stuff
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
//fourth line adds the LocationServices API endpoint from GooglePlayServices
.addApi(LocationServices.API)
.build();
// Create the LocationRequest object
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
activity=(MainActivity)getActivity();
lblTrasaction=(TextView)rootView.findViewById(R.id.lbl_trasaction);
lblTrasaction.setTypeface(AppController.fntAlice);
lblStation=(TextView)rootView.findViewById(R.id.lbl_station);
lblStation.setTypeface(AppController.fntVani);
lblNoBottle=(TextView)rootView.findViewById(R.id.lbl_no_bottle);
lblNoBottle.setTypeface(AppController.fntVani);
lblPointsColl=(TextView)rootView.findViewById(R.id.lbl_points_coll);
lblPointsColl.setTypeface(AppController.fntVani);
lblPoints=(TextView)rootView.findViewById(R.id.lbl_points);
lblPoints.setTypeface(AppController.fntVani);
btnUgc=(Button)rootView.findViewById(R.id.btn_ugc);
btnUgc.setTypeface(AppController.fntVani);
btnMore=(Button)rootView.findViewById(R.id.btn_more);
btnMore.setTypeface(AppController.fntVani);
txtPoints=(TextView)rootView.findViewById(R.id.txt_points);
txtPoints.setTypeface(AppController.fntVani);
if(prefManager.getPoints()==0){
txtPoints.setText("0");
}
else{
txtPoints.setText(""+prefManager.getPoints());
}
if(Utils.isNetworkConnected(getActivity())){
RequestParams params=new RequestParams();
params.put(ApiCalls.REQUEST_CASE_LABEL,"customerHistory");
params.put("postData[customerid]",prefManager.getCustomerId());
getTransactionApiCall(params);
}
else{
Toast.makeText(getActivity(),getString(R.string.internet), Toast.LENGTH_SHORT).show();
}
items=new ArrayList<>();
lvTransaction=(ListView)rootView.findViewById(R.id.lv_transaction);
btnMore.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Message message=new Message();
Bundle bundle=new Bundle();
bundle.putString("more","1");
message.setData(bundle);
activity.uiHandler.sendMessage(message);
}
});
btnUgc.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showDialog();
}
});
return rootView;
}
@Override
public void onResume() {
super.onResume();
mGoogleApiClient.connect();
}
@Override
public void onPause() {
super.onPause();
Log.v(this.getClass().getSimpleName(), "onPause()");
//Disconnect from API onPause()
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
}
@Override
public void onConnected(Bundle bundle) {
if (Build.VERSION.SDK_INT >= 21 &&
ContextCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return ;
}
else {
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
} else {
currentLatitude = location.getLatitude();
currentLongitude = location.getLongitude();
}
}
}
@Override
public void onConnectionSuspended(int i) {}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
connectionResult.startResolutionForResult(getActivity(), CONNECTION_FAILURE_RESOLUTION_REQUEST);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
} else {
Log.e("Error", "Location services connection failed with code " + connectionResult.getErrorCode());
}
}
@Override
public void onLocationChanged(Location location) {
currentLatitude = location.getLatitude();
currentLongitude = location.getLongitude();
}
public void getUcgCallApi(final RequestParams params){
AsyncHttpClient client=new AsyncHttpClient();
client.setTimeout(AsyncHttpClient.DEFAULT_SOCKET_TIMEOUT);
client.post(ApiCalls.API_CALL, params, new AsyncHttpResponseHandler() {
@Override
public void onStart() {
super.onStart();
Log.i(TAG,"GET UGC PARAMS:->>>"+params.toString());
}
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
try{
String str=new String(responseBody);
JSONObject mainObj=new JSONObject(str);
Log.e(TAG,"SUCCESS RESPONSE:=>>"+mainObj.toString());
if(mainObj.has("status") && !mainObj.isNull("status")){
if(mainObj.getString("status").equalsIgnoreCase("Success")){
JSONArray data=mainObj.getJSONArray("data");
JSONObject dataObj=data.getJSONObject(0);
prefManager.setPkUgcId(dataObj.getString("PK_UGC_ID"));
prefManager.setUgcCode(dataObj.getString("UGC_CODE"));
if(!prefManager.getPkUgcId().equals(PreferenceSetting.DEFAULT)){
Log.e(TAG,"UGC ID STORED::"+prefManager.getPkUgcId()+"\nUGC CODE::->"+prefManager.getUgcCode());
Date timeDate=Utils.getDate(Long.parseLong(dataObj.getString("EXPIRED_TIME")));
Log.e(TAG,"DATE UTIL:->"+timeDate);
Date currentDate=new Date();
double LOCATION_LATITUDE=Double.parseDouble(dataObj.getString("LOCATION_LATITUDE"));
double LOCATION_LONGITUDE=Double.parseDouble(dataObj.getString("LOCATION_LONGITUDE"));
Log.e(TAG,"GETCURRENT TIME:->"+currentDate.toString());
if(timeDate.after(currentDate)){
Log.e(TAG,"FIRST DISTANCE:->"+distance(currentLatitude,currentLongitude,LOCATION_LATITUDE,LOCATION_LONGITUDE));
if((distance(currentLatitude,currentLongitude,LOCATION_LATITUDE,LOCATION_LONGITUDE)/1000) <= 5 ) {
Log.e(TAG,"AFTER DISTANCE:->"+distance(currentLatitude,currentLongitude,LOCATION_LATITUDE,LOCATION_LONGITUDE));
RequestParams reqParams = new RequestParams();
reqParams.put(ApiCalls.REQUEST_CASE_LABEL, "UGCReading");
reqParams.put(KEY_UGC, prefManager.getUgcCode());
reqParams.put(KEY_CUSTOMER_ID, prefManager.getCustomerId());
reqParams.put(KEY_UGC_ID, prefManager.getPkUgcId());
// readUgcCodeApiCall(reqParams);
}
else{
Toast.makeText(getActivity(), "“You are out of range for redeem", Toast.LENGTH_SHORT).show();
}
}
if(timeDate.before(currentDate)){
Toast.makeText(getActivity(), "UGC Code Expired", Toast.LENGTH_SHORT).show();
}
}
}
else{
Toast.makeText(getContext(), mainObj.getString("status"), Toast.LENGTH_SHORT).show();
}
}
}
catch (Exception e){
Log.e(TAG,"on Success()==>"+Log.getStackTraceString(e));
}
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
try{
String str=new String(responseBody);
JSONObject mainObj=new JSONObject(str);
Log.e(TAG,"FAILURE RESPONSE:=>>"+mainObj.toString());
}
catch (Exception e){
Log.e(TAG,"on Failure()==>"+Log.getStackTraceString(e));
}
}
});
}
public void readUgcCodeApiCall(final RequestParams params){
AsyncHttpClient client=new AsyncHttpClient();
client.setTimeout(AsyncHttpClient.DEFAULT_SOCKET_TIMEOUT);
client.post(ApiCalls.API_CALL, params, new AsyncHttpResponseHandler() {
@Override
public void onStart() {
super.onStart();
Log.e(TAG,"PARAMS:->>>"+params.toString());
}
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
try {
String str=new String(responseBody);
JSONObject mainObj=new JSONObject(str);
Log.e(TAG,"SUCCESS RESPONSE readUgcCodeApiCall :=>>"+mainObj.toString());
if(mainObj.has("status") && !mainObj.isNull("status")){
if(mainObj.getString("status").equalsIgnoreCase("Success")){
Toast.makeText(getActivity(),getString(R.string.success), Toast.LENGTH_SHORT).show();
RequestParams params=new RequestParams();
params.put(ApiCalls.REQUEST_CASE_LABEL,"customerHistory");
params.put("postData[customerid]",prefManager.getCustomerId());
getTransactionApiCall(params);
}
else{
Toast.makeText(getActivity(),getString(R.string.unsuccess), Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
Log.e(TAG,"on Success()==>"+Log.getStackTraceString(e));
}
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
try {
String str=new String(responseBody);
JSONObject mainObj=new JSONObject(str);
Log.e(TAG,"FAILURE RESPONSE:=>>"+mainObj.toString());
} catch (Exception e) {
Log.e(TAG,"on Failure()==>"+Log.getStackTraceString(e));
}
}
});
}
private double distance(double lat1, double lon1, double lat2, double lon2) {
double theta = lon1 - lon2;
double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta));
dist = Math.acos(dist);
dist = rad2deg(dist);
dist = dist * 60 * 1.1515;
return (dist);
}
private double deg2rad(double deg) {
return (deg * Math.PI / 180.0);
}
private double rad2deg(double rad) {
return (rad * 180.0 / Math.PI);
}
public void showDialog(){
final Dialog dialog=new Dialog(getContext());
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.claim_dialog);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.setCanceledOnTouchOutside(true);
dialog.setCancelable(true);
final EditText editClaim=(EditText)dialog.findViewById(R.id.edit_claim);
// editClaim.setTypeface(AppController.fntVani);
Button btnClaim=(Button)dialog.findViewById(R.id.btn_claim);
btnClaim.setTypeface(AppController.fntVani);
btnClaim.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(!editClaim.getText().toString().trim().equals("")) {
if (Utils.isNetworkConnected(getActivity())) {
RequestParams params=new RequestParams();
params.put(ApiCalls.REQUEST_CASE_LABEL,"getUGCDetails");
params.put(KEY_UGC,editClaim.getText().toString().trim());
getUcgCallApi(params);
if(dialog.isShowing()){
dialog.dismiss();
}
} else {
Toast.makeText(getContext(), getString(R.string.internet), Toast.LENGTH_SHORT).show();
}
}
}
});
dialog.show();
}
}
公共类HomeFragment扩展片段实现ConnectionCallbacks、OnConnectionFailedListener、LocationListener{
公共静态最终字符串标记=TransactionFragment.class.getSimpleName();
公共静态最终字符串键_UGC=“postData[UGC]”;
公共静态最终字符串键\u CUSTOMER\u ID=“postData[customerid]”;
公共静态最终字符串键_UGC_ID=“postData[ugcid]”;
视图根视图;
优先权设定经理;
ListView lvTransaction;
清单项目;
TextView txtPoints;
按钮btnUgc,btnMore;
列表事务列表;
text查看LBLtraAction、lblStation、lblNoBottle、lblPointsColl、lblPoints;
int totalPoints=0;
主要活动;
专用最终静态int连接\故障\解决\请求=9000;
私人GoogleapClient MGoogleapClient;
私人位置请求mLocationRequest;
私人双纬度;
私人双保险;
@可空
@凌驾
创建视图时的公共视图(LayoutFlater充气机、@Nullable ViewGroup容器、@Nullable Bundle savedInstanceState){
rootView=充气机。充气(R.布局。碎片_home,容器,false);
prefManager=PreferenceSetting.getInstance(getActivity());
mgoogleapclient=新的Googleapclient.Builder(getActivity())
//接下来的两行告诉新客户机“this”当前类将处理连接内容
.addConnectionCallbacks(此)
.addOnConnectionFailedListener(此)
//第四行添加了Google PlayServices中的LocationServices API端点
.addApi(LocationServices.API)
.build();
//创建LocationRequest对象
mLocationRequest=LocationRequest.create()
.setPriority(定位请求。优先级高精度)
.setInterval(10*1000)//10秒,以毫秒为单位
.setFastTestInterval(1*1000);//1秒,以毫秒为单位
活动=(MainActivity)getActivity();
lblTrasaction=(TextView)rootView.findViewById(R.id.lbl_trasaction);
lblTrasaction.setTypeface(AppController.fntAlice);
lblStation=(TextView)rootView.findviewbyd(R.id.lbl_站);
lblStation.setTypeface(AppController.fntVani);
lblNoBottle=(TextView)rootView.findViewById(R.id.lbl\u no\u瓶子);
lblNoBottle.setTypeface(AppController.fntVani);
lblPointsColl=(TextView)rootView.findViewById(R.id.lbl\u points\u coll);
lblPointsColl.setTypeface(AppController.fntVani);
lblPoints=(TextView)rootView.findViewById(R.id.lbl_点);
lblPoints.setTypeface(AppController.fntVani);
btnUgc=(按钮)rootView.findviewbyd(R.id.btn_ugc);
btnUgc.setTypeface(AppController.fntVani);
btnMore=(按钮)rootView.findviewbyd(R.id.btn\u more);
btnMore.setTypeface(AppController.fntVani);
txtPoints=(TextView)rootView.findViewById(R.id.txt_points);
设置字体(AppController.fntVani);
if(prefManager.getPoints()==0){
txtPoints.setText(“0”);
}
否则{
setText(“+prefManager.getPoints());
}
if(Utils.isNetworkConnected(getActivity())){
RequestParams params=新的RequestParams();
参数put(ApiCalls.REQUEST_CASE_标签,“customerHistory”);
put(“postData[customerid]”,prefManager.getCustomerId());
getTransactionApiCall(参数);
}
否则{
Toast.makeText(getActivity()、getString(R.string.internet)、Toast.LENGTH_SHORT.show();
}
items=newarraylist();
lvTransaction=(ListView)rootView.findviewbyd(R.id.lv_事务);
btnMore.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图){
消息消息=新消息();
Bundle=新Bundle();
bundle.putString(“更多”、“1”);
message.setData(bundle);
activity.uiHandler.sendMessage(消息);
}
});
btnUgc.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图){
showDialog();
}
});
返回rootView;
}
@凌驾
恢复时公开作废(){
super.onResume();
mGoogleApiClient.connect();
}
@凌驾
公共无效暂停(){
super.onPause();
Log.v(this.getClass().getSimpleName(),“onPause()”);
//断开与API onPause()的连接
if(mgoogleapClient.isConnected()){
LocationServices.FusedLocationApi.RemovelocationUpdate(mgoogleapClient,this);
mGoogleApiClient.disconnect();
}
}
@凌驾
未连接的公共空间(捆绑包){
如果(Build.VERSION.SDK_INT>=21&&
ContextCompat.checkSelfPermission(getActivity(),android.Manifest.permission.ACCESS\u FINE\u LOCATION)!=PackageManager.permission\u已授予&&
ContextCompat.checkSelfPermission(getActivity(),android.Manifest.permission.ACCESS\u\u LOCATION)!=PackageManager.permission\u已授予){
float[] distance = new float[1];
Location.distanceBetween(mLocation.latitude, mLocation.longitude, locations.latitude, locations.longitude, distance);
public static float distFrom(float lat1, float lng1, float lat2, float lng2) {
double earthRadius = 6371000; //meters
double dLat = Math.toRadians(lat2-lat1);
double dLng = Math.toRadians(lng2-lng1);
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
Math.sin(dLng/2) * Math.sin(dLng/2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
float dist = (float) (earthRadius * c);
return dist;
}
float meter= distFrom(LOCATION_LATITUDE1,LOCATION_LONGITUDE2,LOCATION_LATITUDE2,LOCATION_LONGITUDE2);
final float kilometer=meter/1000;