如何使用LatLng从google Place API中找到附近的地方。

问题描述 投票:0回答:1

所以,我有一个使用地图api打开uo google的活动,我能够用自动完成搜索的地方,但我如何使用LatLng获得neasrt "地方"?

更多细节,在活动Luanch上,它返回最后已知的位置作为用户的当前位置,但这只是LatLng,我如何使用这个LatLng来获得附近的地方?场所 使用 google place api.

谢谢你。

public class Map extends AppCompatActivity {
    //google map required variables
    private static final String TAG = "MapActivity";
    private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
    private static final String COURSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
    private static final float ZOOMING_DEFAULT = 18.0f;
    private static final int LOCATION_PERMISSION_REQUEST_CODE = 9999;
    private SupportMapFragment MysupportMapFragment;
    private FusedLocationProviderClient MyfusedLocationProviderClient;
    private GoogleMap MyMap;
    private static final int AUTOCOMPLETE_REQUEST_CODE = 1;
    //local variables
    private Boolean  MyLocationPermissionsGranted = false;
    private Location Mylocation;
    private LatLng MylatLng;
    private List<Place.Field> fieldList;
    private Place AutocompletedPlaces;
    //need to be accessed in multiple activities/classes
    private LatLng SearchedLocationlatLng;
    private String SearchedlocationAddress;
    private String SearchedlocationName;
    //widgets
    private EditText editTextsearchlocation;
    private Button btnConfirmAddress;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map);

        MysupportMapFragment
                = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.fragment_map);

        MyfusedLocationProviderClient
                = LocationServices.getFusedLocationProviderClient(this);

        if (checkLocationPermission()){
            getCurrentLocation();
        }

        Log.d(TAG, "onCreate: initializing GOOGLE Places");
        Places.initialize(getApplicationContext(),"API_KEY");

        editTextsearchlocation = findViewById(R.id.edittext_SearchBar);
        editTextsearchlocation.setFocusable(false);
        editTextsearchlocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "onClick: initialize place field list");
                fieldList = Arrays.asList(Place.Field.ADDRESS,Place.Field.LAT_LNG,Place.Field.NAME);
                Log.d(TAG, "onClick: initialize place autoComplete");
                Intent searchPlaceIntent = new Autocomplete.IntentBuilder(
                        AutocompleteActivityMode.OVERLAY, fieldList).build(Map.this);
                startActivityForResult(searchPlaceIntent,AUTOCOMPLETE_REQUEST_CODE);
            }
        });

        btnConfirmAddress = findViewById(R.id.btnConfirmSearchedAddress);
        btnConfirmAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //passlocation to checkin fragment
                //code incomplete
                //Also trying to find out how to pass data from multiple activity to one activity's fragment.
                finish();
            }
        });

    }

//    above for btnConfirmAddress
//    When you call an activity from other activity's fragment, then the previous activity's instance
//    state that is the calling activity which was having fragment's instance state will be saved
//    in stack...so all u need to do is finish the called activity and u will have the fragment
//    from which you called your second activity.

    private boolean checkLocationPermission() {
        Log.d(TAG, "getLocationPermission: getting Location Permission");
        String[] permissions = {FINE_LOCATION,COURSE_LOCATION};

        if (ContextCompat.checkSelfPermission(this.getApplicationContext(),FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED){
            if (ContextCompat.checkSelfPermission(this.getApplicationContext(),COURSE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED)
            {
                Log.d(TAG, "CheckLocationPermission: All permisiion Granted,Continue.");
                //
                return true;
            } else {
                Log.d(TAG, "CheckLocationPermission: Request For COURSE_LOCATION");
                ActivityCompat.requestPermissions(this,permissions
                        ,LOCATION_PERMISSION_REQUEST_CODE);
                return false;
            }
        } else {
            Log.d(TAG, "CheckLocationPermission: Request For FINE_LOCATION");
            ActivityCompat.requestPermissions(this,permissions
                    ,LOCATION_PERMISSION_REQUEST_CODE);
            return false;
        }
    }

    private void getCurrentLocation() {
        Log.d(TAG, "GetCurrentLocation: Getting Last Known Location from System");
        Task<Location> task = MyfusedLocationProviderClient.getLastLocation();
        task.addOnSuccessListener(new OnSuccessListener<Location>() {
            @Override
            public void onSuccess(final Location location) {
                if (location != null){
                    Mylocation=location;
                    initializeMap(Mylocation);
                }
            }
        });
    }

    private void initializeMap(final Location location) {
        Log.d(TAG, "onSuccess: Successfully Obtaining Last Known Location");

        MysupportMapFragment.getMapAsync(new OnMapReadyCallback() {
            @Override
            public void onMapReady(GoogleMap googleMap) {
                Log.d(TAG, "onMapReady: Initialize Latitude and Longitude");
                MyMap = googleMap;
                MylatLng = new LatLng(location.getLatitude()
                        ,location.getLongitude());
                Log.d(TAG, "onMapReady: Drop A Marker On My current location");
                MarkerOptions Marker = new MarkerOptions().position(MylatLng)
                        .title("Your Current Location");
                MyMap.addMarker(Marker);
                Log.d(TAG, "onMapReady: Zoom on top My Location");
                MyMap.animateCamera(CameraUpdateFactory
                        .newLatLngZoom(MylatLng,ZOOMING_DEFAULT));
                //disable the compass(might creat my own later or come back to change the position)
                MyMap.getUiSettings().setCompassEnabled(false);
                //disable direction and show it in google map
                MyMap.getUiSettings().setMapToolbarEnabled(false);
                MyMap.getUiSettings().setZoomControlsEnabled(true);

            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        Log.d(TAG, "onRequestPermissionsResult: called");
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        MyLocationPermissionsGranted = false;

        switch (requestCode){
            case LOCATION_PERMISSION_REQUEST_CODE:{
                if (grantResults.length > 0 ){
                    for (int i = 0; i < grantResults.length; i++) {
                        if (grantResults[i] == PackageManager.PERMISSION_GRANTED){
                            MyLocationPermissionsGranted=false;
                            Log.d(TAG, "onRequestPermissionsResult: permission failed");
                            return;
                        }
                    }
                    Log.d(TAG, "onRequestPermissionsResult: permission granted");
                    MyLocationPermissionsGranted=true;
                    //initialize map
                    getCurrentLocation();
                }
            }
        }
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d(TAG, "onActivityResult: currently at onActivityResult");
        if (requestCode == AUTOCOMPLETE_REQUEST_CODE) {
            Log.d(TAG, "onActivityResult: Correct Request Code");
            if (resultCode == AutocompleteActivity.RESULT_OK) {
                Log.d(TAG, "onActivityResult: successfully Obtaining Places");
                AutocompletedPlaces = Autocomplete.getPlaceFromIntent(data);
                Log.i(TAG, "Place: "
                        + AutocompletedPlaces.getName() + ", "
                        + AutocompletedPlaces.getId());
                SearchedLocationlatLng = AutocompletedPlaces.getLatLng();
                SearchedlocationAddress = AutocompletedPlaces.getAddress();
                SearchedlocationName = AutocompletedPlaces.getName();
                editTextsearchlocation.setText(SearchedlocationAddress);
                moveCamera(SearchedLocationlatLng,ZOOMING_DEFAULT,SearchedlocationName,SearchedlocationAddress);
            } else if (resultCode == AutocompleteActivity.RESULT_ERROR) {
                Log.d(TAG, "onActivityResult: Failed To Obtaining Places");
                Status status = Autocomplete.getStatusFromIntent(data);
                Log.i(TAG, status.getStatusMessage());
            } else if (resultCode == RESULT_CANCELED) {
                // The user canceled the operation.
            }

        }
    }

    private void moveCamera(LatLng latLng, float zoom, String title,String subtitle){
        Log.d(TAG, "moveCamera: moving the camera to : Latitude:" + latLng.latitude + ", Longitude: " +latLng.longitude);
        MyMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,zoom));

        //dont drop a pin on my location
        if (!title.equals("My Location")){
            //code below drop a pin on the map when camera moved
            MarkerOptions markerOptions = new MarkerOptions().position(latLng).title(title).snippet(subtitle);
            MyMap.addMarker(markerOptions);
        }

    }

    @Override
    public void onBackPressed() {
//        super.onBackPressed();
        //allow back condition
        if (false) {
            super.onBackPressed();
        }
        //no back is allowed
        else {
        }
//        finish();
    }
}

java android android-studio google-places-api google-places
1个回答
0
投票
© www.soinside.com 2019 - 2024. All rights reserved.