Solution 1 :
As
map.getMyLocation()
is depracated you can try this:
public Location getLocation() {
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
if (locationManager != null) {
Location lastKnownLocationGPS = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (lastKnownLocationGPS != null) {
return lastKnownLocationGPS;
} else {
return locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
}
} else {
return null;
}
}
And dont forget about permissions (runtime and in manifest).
Problem :
I have a google maps in one fragment in my app. How can I get the current location and show nearby car services?
package com.example.easyauto;
import android.location.Location;
import android.os.Bundle;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class HartaFragment extends Fragment implements OnMapReadyCallback {
View view; // for the view
GoogleMap map; // for the GoogleMaps
MapView mapView;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_harta, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mapView = view.findViewById(R.id.mapsView);
if(mapView != null){
mapView.onCreate(null);
mapView.onResume();
mapView.getMapAsync(this);
}
}
@Override
public void onMapReady(GoogleMap googleMap) {
MapsInitializer.initialize(getContext());
map = googleMap; // show the maps ok
}
}
This is the code I wrote for now. It all works fine. Do I need also to put tha map_fragment.xml here for more details?
I also added the meta-data for google maps and the implementation ‘com.google.android.gms:play-services-maps:16.1.0’,
Comments
Comment posted by Codelab
Welcome to StackOverflow. I would recommend to be more concise in your questions to be easier to answer for other people. You aren’t quite asking a question, but asking for someone else to do it for you. I would hardly recommend to follow some sort of