简体   繁体   中英

How to set text to Google Maps current location from another class

I created a seperate activity to create a Google Map and set a marker on the users current location. In another fragment class, I'd like to set the text of a text view to the location from the map activity.

CheckInFragment

mLocation = (TextView) v.findViewById(R.id.checkin_location_text);
mLocation.setText();

MapsActivity

private void handleNewLocation(Location location){
    //SET THESE TWO VARIABLES TO THE TEXT vv
    double currentLatitude = location.getLatitude();
    double currentLongitude = location.getLongitude();

    LatLng latLng = new LatLng(currentLatitude, currentLongitude);

    MarkerOptions options = new MarkerOptions()
                .position(latLng)
                .title("Check In Location");

    mMap.addMarker(options); 
    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    float zoomLevel = 16.0f;
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoomLevel));

}

You can try below code to get the string value of location:

Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
    List<Address> addressList = geocoder.getFromLocation(location.getLatitude(),
                        location.getLongitude(), 1);

    String fullAddress = "";

    if (addressList != null && addressList.size() > 0) {

        if (addressList.get(0).getAddressLine(0) != null) {
            fullAddress += addressList.get(0).getAddressLine(0) + " ";
        }
        if (addressList.get(0).getSubAdminArea() != null) {
            fullAddress += addressList.get(0).getSubAdminArea() + " ";
        }

    } else {
        Log.d("Address:", "Couldn't find Address");
    }
} catch (IOException e) {
    e.printStackTrace();
}

Then you can pass the fullAddress string value in a bundle when calling the your fragment class, something like:

YourFragment fragment = new YourFragment();
Bundle args = new Bundle();
args.putString("location_string", fullAddress);
fragment.setArguments(args);

Finally in onCreate method of your Fragment class fetch the string value as below:

if (getArguments() != null)
{
    _location = getArguments().getString("location_string");
}

Hope this helps!!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM