Question

Well, below is my example, I have a main activity in Android, and I have create a toolbar, and there is a sub function called location which I will call some location function here. It is coded in a fragment because I need to create a fragment when I get into the sub function after I click the icon from the toolbar.

I have got how to show the google map inside a activity. But I failed to show it in a fragment. What I can do is just to call a onActivityCreated inside a fragment. However, although the program works fine, but the layout will omit the toolbar.(I am not good at English, if you don't understand what I am talking about, just ask me for details:))

So does anyone could help me to figure out how to call some google location services such as find the png and lat, or showing the google map inside a fragment? My fragment code is in below:

LocationFragment.java:

public class LocationFragment extends MapFragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View location_layout = inflater.inflate(R.layout.location_layout, container, false);
        return location_layout;
    }
}
Was it helpful?

Solution

Your fragment class will be:

public class MyFragment extends Fragment {

    private MapView mapView;
    private GoogleMap map;
    private Bundle bundle;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
       View v = inflater.inflate(R.layout.fragment_map, container, false);

       // initialize it to avoid a NPE
       try {
           MapsInitializer.initialize(getActivity());
       } catch (GooglePlayServicesNotAvailableException e) { }

       mapView = (MapView) v.findViewById(R.id.map);
       mapView.onCreate(bundle);

       // check if the map is null
       if (map == null) {
           map = ((MapView) v.findViewById(R.id.map)).getMap();
       }

       // add a marker
       map.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Here!"));

       return v;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        bundle = savedInstanceState;
    }

    @Override
    public void onResume() {
       super.onResume();
       mapView.onResume();
    }

    @Override
    public void onPause() {
       super.onPause();
       mapView.onPause();
    }

    @Override
    public void onDestroy() {
       mapView.onDestroy();
       super.onDestroy();
    }

    @Override  
    public void onLowMemory() {  
        super.onLowMemory();  
        mapView.onLowMemory();  
    }  
}

And finally, your layout fragment_map:

<com.google.android.gms.maps.MapView 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/map"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" />  

He' we go to show your map inside a fragment! See a little post on it and the reference from Google.

For user's Location, a bit of reading is necessary, just to know more about it: Location Strategies (read carefully, everything is tell there). You'll need a Location Manager and a Location Listener.
First of all, you need this implements:

// The implement
implements LocationListener { [...] }  

With this listener, you will able to have and update the location of the device via GPS or network. Don't forget to test the status of the device's service, something like this:

// Getting Google Play availability status
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());  

This code below is an example to get the current location inside a fragment:

public class LocationFragment extends Fragment implements LocationListener {

    private Marker marker;
    private LocationManager locationManager;

    static final LatLng NEWYORK = new LatLng(40.75, -74.03);

    @Override  
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {  
        super.onCreateView(inflater, container, savedInstanceState);
        View v = inflater.inflate(R.layout.location_layout, container, false);

        // ... 
        if (map == null) {
            map = ((MapView) v.findViewById(R.id.map)).getMap();
        }
        // ...
        if (map != null) initMap();

        locationManager = (LocationManager) getActivity().getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
        if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            getGPS();
        } else {
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 10, this);    
        }
        // ...

        return v;
    }

    @Override
    public void onResume() {
        super.onResume();
        getGPS();
    }

    @Override
    public void onPause() {
        super.onPause();
        outGPS();
    }

    public void getGPS() {
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 10, this);
    }

    public void outGPS() {
        locationManager.removeUpdates(this);
    }

    @Override
    public void onLocationChanged(final Location location) {
        // get the latitude and the longitude
        final StringBuilder msg = new StringBuilder("lat : ");
        msg.append(location.getLatitude());
        msg.append( "; lng : ");
        msg.append(location.getLongitude());
        // display it on a toast
        Toast.makeText(getActivity().getApplicationContext(), msg.toString(), Toast.LENGTH_SHORT).show();

        // final latlng with these above to update the position on a marker
        final LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        gMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 1));
        marker.setPosition(latLng);
        // ...
    }

    @Override
    public void onProviderDisabled(final String provider) {
        if("gps".equals(provider)) {
            desabonnementGPS();
        }
    }

    @Override
    public void onProviderEnabled(final String provider) {
        if("gps".equals(provider)) {
            abonnementGPS();
        }
    }

    @Override
    public void onStatusChanged(final String provider, final int status, final Bundle extras) { }

    private void initMap() {
        gMap.addMarker(new MarkerOptions().title("New-York").position(NEWYORK));
        marker = gMap.addMarker(new MarkerOptions().title("I am here!").position(new LatLng(0, 0)));
    }
}

Then you create the manager and after you update the current location with the onLocationChanged method. There some good tutorials about it: a tutorial by Vogella (it might be help) and another tutorial (can help you too).

You have a lot of tips on this blog. Very simple, very comprehensive.

NOTE2: DON'T FORGET TO ADD THE PERMISSIONS IN YOUR MANIFEST.

I hope, I answered clearly and this will be useful.
Happy coding!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top