靠近android中的位置坐标

时间:2017-03-07 04:55:20

标签: android android-studio geolocation

我找到了获取该位置纬度和经度的代码。现在,我想找到一个靠近的位置。就像在附近找到一家餐馆一样。

所以,如果我搜索地铁,我应该得到近地铁的坐标

我怎样才能到达附近?我想要只是坐标..谷歌地图中没有任何东西。

2 个答案:

答案 0 :(得分:0)

请参阅Google Places Api:https://developers.google.com/places/

答案 1 :(得分:0)

使用以下课程获取位置 的被修改

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.widget.Toast;


import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResult;
import com.google.android.gms.location.LocationSettingsStatusCodes;


public class LocationService implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener,
        ActivityCompat.OnRequestPermissionsResultCallback {


    private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;
    private static int DISPLACEMENT = 3; // 3 meters

    private static int UPDATE_INTERVAL = 10000; // 10 sec
    private static int FATEST_INTERVAL = 10000; // 10 sec

    private static String[] PERMISSIONS = {Manifest.permission.ACCESS_FINE_LOCATION};
    private static final int PERMISSIONS_REQUEST = 0;

    protected GoogleApiClient mGoogleApiClient;
    protected LocationRequest mLocationRequest;

    Location mCurrentLocation;
    public double locationLatitude = 0.0, locationLongitude = 0.0;
    Context context;
    private static LocationService locationService;

    public LocationService(Context context) {
        this.context = context;

        if (checkPlayServices()) {
            buildGoogleApiClient();
            createLocationRequest();
            checkPermissionForLocation();
        }

        // Resuming the periodic location updates
        if (mGoogleApiClient != null) {
            mGoogleApiClient.connect();
            if (mGoogleApiClient.isConnected()) {
                startLocationUpdates();
            }
        }
    }

    public static LocationService getInstance(Context con) {
        if (locationService == null) {
            locationService = new LocationService(con);
        }
        return locationService;
    }

    public void checkPermissionForLocation() {
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
            requestLocationPermission();
        else
            locationChecker(mGoogleApiClient);
    }

    @Override
    public void onLocationChanged(Location location) {
        mCurrentLocation = location;
        displayLocation();
    }

    @Override
    public void onConnected(Bundle bundle) {
        //displayLocation();
        startLocationUpdates();
        displayLocation();
    }

    @Override
    public void onConnectionSuspended(int i) {
        mGoogleApiClient.connect();
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        buildGoogleApiClient();
    }


    public void startLocationUpdates() {
        if (checkPermission(context)) {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, (com.google.android.gms.location.LocationListener) this);
        }
    }

    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(context)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API).build();
    }

    private boolean checkPlayServices() {
        if (isAvailablePlayService((Activity) context)) {
            return true;
        } else {
            checkGooglePlayservice((Activity) context);
            Toast.makeText(context,
                    "This device is not supported.", Toast.LENGTH_LONG)
                    .show();
            return false;
        }
    }

    public static void checkGooglePlayservice(Activity activity) {
        // Getting status
        GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
        int status = googleAPI.isGooglePlayServicesAvailable(activity.getBaseContext());

        // Showing status
        if (status == ConnectionResult.SUCCESS) {

        } else {
            int requestCode = 10;
            Dialog dialog = googleAPI.getErrorDialog(activity, status, requestCode);
            dialog.setCanceledOnTouchOutside(false);
            dialog.setCancelable(false);
            dialog.show();
        }
    }

    public static boolean isAvailablePlayService(Activity activity) {
        GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
        return (Boolean) (googleAPI.isGooglePlayServicesAvailable(activity.getBaseContext()) == ConnectionResult.SUCCESS);
    }

    protected void createLocationRequest() {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(UPDATE_INTERVAL);
        mLocationRequest.setFastestInterval(FATEST_INTERVAL);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setSmallestDisplacement(DISPLACEMENT); // 3 meters
    }

    public void displayLocation() {
        if (mGoogleApiClient != null)
            if (checkPermission(context)) {
                mCurrentLocation = LocationServices.FusedLocationApi
                        .getLastLocation(mGoogleApiClient);

                if (mCurrentLocation != null) {
                    locationLatitude = mCurrentLocation.getLatitude();
                    locationLongitude = mCurrentLocation.getLongitude();

                /*Utility.showToast(context, "Latitude : " + locationLatitude +"Longitude : "+ locationLongitude);
                Utility.showToast(context, "Speed : " + mCurrentLocation.getSpeed());
                Utility.showToast(context, "Speed in kmph : " + mCurrentLocation.getSpeed() * 3600 / 1000);*/

                } else {
//                Utility.showToast(context, "Couldn't get the location. Make sure location is enabled on the device");
                }
            }
    }

    @TargetApi(Build.VERSION_CODES.M)
    private void requestLocationPermission() {
        if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.ACCESS_FINE_LOCATION)) {
            /*Snackbar.make(parent, "Location access is required for app", Snackbar.LENGTH_INDEFINITE).setAction("OK", new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    requestPermissions(PERMISSIONS, PERMISSIONS_REQUEST);
                }
            }).show();*/
            Toast.makeText(context, "Location access is required for app", Toast.LENGTH_SHORT).show();
            ((Activity) context).requestPermissions(PERMISSIONS, PERMISSIONS_REQUEST);
        } else {
            ((Activity) context).requestPermissions(PERMISSIONS, PERMISSIONS_REQUEST);
        }
    }

    public void locationChecker(GoogleApiClient mGoogleApiClient) {
        LocationRequest locationRequest = LocationRequest.create();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        locationRequest.setInterval(10 * 1000);
        locationRequest.setFastestInterval(5 * 1000);
        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);
        builder.setAlwaysShow(true);

        PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
        result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
            @Override
            public void onResult(LocationSettingsResult result) {
                final Status status = result.getStatus();
                switch (status.getStatusCode()) {
                    case LocationSettingsStatusCodes.SUCCESS:
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                displayLocation();
                            }
                        }, 1000);
                        break;
                    case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                        try {
                            //---------We are showing location dialog every "LOCATION_COUNT_GAP" TIMES
//                            if(UMApp.getApp().locationDialogCount%UMApp.getApp().LOCATION_COUNT_GAP==0){
                            status.startResolutionForResult((Activity) context, 1000);
//                            }
//                            UMApp.getApp().locationDialogCount++;
                        } catch (IntentSender.SendIntentException e) {
                            e.printStackTrace();
                        }
                        break;
                }
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case PERMISSIONS_REQUEST: {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // permission was granted, yay! do the
                    // calendar task you need to do.
                    startLocationUpdates();
                    locationChecker(mGoogleApiClient);
                } else {
                    Toast.makeText(context, "Permission not granted, Please try again.", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    private boolean checkPermission(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                    ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return false;
            } else {
                return true;
            }
        } else {
            return true;
        }
    }

    public void stopLocationUpdates() {
        if (mGoogleApiClient != null)
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
    }

    /*Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
    Uri uri = Uri.fromParts("package", getPackageName(), null);
    intent.setData(uri);
    startActivityForResult(intent, REQUEST_PERMISSION_SETTING);*/
}