簡體   English   中英

如何在 getMyLocationAddress 方法的 onLocationChanged 中訪問我的當前位置?

[英]How can I access my current location in onLocationChanged, in getMyLocationAddress method?

我想訪問我在 getMyLocationAddress 中的 onLocationChanged 方法中的當前位置以設置文本框的文本。 我想知道我的位置准確存儲在哪個變量中,以便我可以在 geocoder.getLocationFrom() 中使用它。

我在 geocoder.getFromLocation(latLng.getLatitude(),latLng.getLongitude(),1); 中使用 LatLng 對象 latLng; 我猜這是存儲當前位置的地方。但是 getFromLocation 需要 Location 對象。 我應該使用哪個 Location 對象作為 LatLng 對象顯然會出錯?

@Override
    public void onLocationChanged(Location location) {

        mLastLocation = location;
        if (mCurrLocationMarker != null) {
            mCurrLocationMarker.remove();
        }

        //Place current location marker
        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(latLng);
        markerOptions.title("Current Position");
        markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
        mCurrLocationMarker = mMap.addMarker(markerOptions);

        //move map camera
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        mMap.animateCamera(CameraUpdateFactory.zoomTo(50));

        //stop location updates
        if (mGoogleApiClient != null) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        }

    }


 public void getMyLocationAddress() {

    Geocoder geocoder= new Geocoder(this, Locale.ENGLISH);

    try {

        //Place your latitude and longitude
       //List<Address> addresses = geocoder.getFromLocation(37.423247,-122.085469, 1);
        List<Address> addresses = geocoder.getFromLocation(latLng.getLatitude(),latLng.getLongitude(),1);

        if(addresses != null) {

            Address fetchedAddress = addresses.get(0);
            StringBuilder strAddress = new StringBuilder();

            for(int i=0; i<fetchedAddress.getMaxAddressLineIndex(); i++) {
                strAddress.append(fetchedAddress.getAddressLine(i)).append("\n");
            }

            etOrigin.setText(strAddress.toString());

        }

        else
            etOrigin.setText("No location found..!");

    }
    catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Toast.makeText(getApplicationContext(),"Could not get address..!", Toast.LENGTH_LONG).show();
    }
}

您需要使用位置類型的變量。

您可以在此處閱讀更多信息: https : //developer.android.com/reference/android/location/Location.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM