Map show current location

Asked

Viewed 1,559 times

7

I would like to know how to make the map show the current location of the user.

I created this code that apparently was working, only sometimes it fails to catch the location and application of the error.

public class VisualizarMapa extends FragmentActivity {

protected GoogleMap map;


@Override
protected void onCreate(Bundle icicle) {

    super.onCreate(icicle);
    setContentView(R.layout.visualizarmapa);

    getActionBar().setTitle("Visualizar Mapa");
    getActionBar().setIcon(new ColorDrawable(getResources().getColor(android.R.color.transparent)));

    SetupMapNull();


}


private void SetupMapNull(){

    if (map == null){

        map = ((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map)).getMap();

        if(map != null){
            setUpMap();
        }

    }

}

private void setUpMap() {

    map.setMyLocationEnabled(true);

    LocationManager locationmanager = (LocationManager)getSystemService(LOCATION_SERVICE);

    Criteria criteria = new Criteria();

    String provider = locationmanager.getBestProvider(criteria, true);

    Location localatual = locationmanager.getLastKnownLocation(provider);

    map.setMapType(map.MAP_TYPE_HYBRID);

    double lat = localatual.getLatitude();
    double longi = localatual.getLongitude();

    LatLng LatLong = new LatLng(lat, longi);

    map.moveCamera(CameraUpdateFactory.newLatLng(LatLong));

    map.animateCamera(CameraUpdateFactory.zoomTo(19));

}

}

Logcat:

02-02 23:13:37.267: E/AndroidRuntime(9556): Process: br.find.me, PID: 9556
02-02 23:13:37.267: E/AndroidRuntime(9556): java.lang.RuntimeException: Unable to start activity ComponentInfo{br.find.me/br.find.me.VisualizarMapa}: java.lang.NullPointerException
02-02 23:13:37.267: E/AndroidRuntime(9556):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2202)
02-02 23:13:37.267: E/AndroidRuntime(9556):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2252)
02-02 23:13:37.267: E/AndroidRuntime(9556):     at android.app.ActivityThread.access$800(ActivityThread.java:139)
02-02 23:13:37.267: E/AndroidRuntime(9556):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1200)
02-02 23:13:37.267: E/AndroidRuntime(9556):     at android.os.Handler.dispatchMessage(Handler.java:102)
02-02 23:13:37.267: E/AndroidRuntime(9556):     at android.os.Looper.loop(Looper.java:136)
02-02 23:13:37.267: E/AndroidRuntime(9556):     at android.app.ActivityThread.main(ActivityThread.java:5103)
02-02 23:13:37.267: E/AndroidRuntime(9556):     at java.lang.reflect.Method.invokeNative(Native Method)
02-02 23:13:37.267: E/AndroidRuntime(9556):     at java.lang.reflect.Method.invoke(Method.java:515)
02-02 23:13:37.267: E/AndroidRuntime(9556):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
02-02 23:13:37.267: E/AndroidRuntime(9556):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:606)
02-02 23:13:37.267: E/AndroidRuntime(9556):     at dalvik.system.NativeStart.main(Native Method)
02-02 23:13:37.267: E/AndroidRuntime(9556): Caused by: java.lang.NullPointerException
02-02 23:13:37.267: E/AndroidRuntime(9556):     at br.find.me.VisualizarMapa.setUpMap(VisualizarMapa.java:70)
02-02 23:13:37.267: E/AndroidRuntime(9556):     at br.find.me.VisualizarMapa.SetupMapNull(VisualizarMapa.java:49)
02-02 23:13:37.267: E/AndroidRuntime(9556):     at br.find.me.VisualizarMapa.onCreate(VisualizarMapa.java:36)
02-02 23:13:37.267: E/AndroidRuntime(9556):     at android.app.Activity.performCreate(Activity.java:5275)
02-02 23:13:37.267: E/AndroidRuntime(9556):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
02-02 23:13:37.267: E/AndroidRuntime(9556):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2166)
  • And what’s the mistake? Edith your question including that information.

  • 1

    I just edited!!!

3 answers

2

I used the code below:

private GoogleMap.OnMyLocationChangeListener myLocationChangeListener = new GoogleMap.OnMyLocationChangeListener() {
    @Override
    public void onMyLocationChange(Location location) {
        LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
        mMarker = mMap.addMarker(new MarkerOptions().position(loc));
        if(mMap != null){
            mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f));
        }
    }
};

Then set on your map:

mMap.setOnMyLocationChangeListener(myLocationChangeListener);

0

That’s how I do

private FusedLocationProviderClient mFusedLocationProvider;
MapView mMapView;
GoogleMap googleMap;

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

    mMapView = (MapView) rootView.findViewById(R.id.mapView);
    mMapView.onCreate(savedInstanceState);

    mMapView.onResume(); // needed to get the map to display immediately

    mFusedLocationProvider = LocationServices.getFusedLocationProviderClient(getActivity());

    try {
        MapsInitializer.initialize(getActivity().getApplicationContext());
    } catch (Exception e) {
        e.printStackTrace();
    }

    mMapView.getMapAsync(new OnMapReadyCallback() {
        @Override
        public void onMapReady(GoogleMap mMap) {
            googleMap = mMap;

            googleMap.setBuildingsEnabled(false);
            if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
                return;
            } else {
                googleMap.setMyLocationEnabled(true);

                mFusedLocationProvider.getLastLocation()
                        .addOnSuccessListener(getActivity(), new OnSuccessListener<Location>() {
                            @Override
                            public void onSuccess(Location location) {
                                // Got last known location. In some rare situations this can be null.
                                if (location != null) {
                                    googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 13));

                                    CameraPosition cameraPosition = new CameraPosition.Builder()
                                            .target(new LatLng(location.getLatitude(), location.getLongitude()))      // Sets the center of the map to location user
                                            .zoom(14)                   // Sets the zoom
                                            .build();                   // Creates a CameraPosition from the builder
                                    googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

                                }
                            }
                        });

            }

        }
    });

    return rootView;
}

This code also shows how I select the map if necessary

0

Man, try this on:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.the_map)).getMap();

    mMap.setMyLocationEnabled(true);

    myPosition = getMyLocation();

    markerClicked = true;
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(myPosition, 18));

}

private LatLng pegaMyLocation(){
    try{
        // Getting LocationManager object from System Service LOCATION_SERVICE
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        // Creating a criteria object to retrieve provider
        Criteria criteria = new Criteria();

        // Getting the name of the best provider
        String provider = locationManager.getBestProvider(criteria, true);
        // Getting Current Location
        Location location = locationManager.getLastKnownLocation(provider);

        if(location!=null){
            // Getting latitude of the current location
            double latitude = location.getLatitude();

            // Getting longitude of the current location
            double longitude = location.getLongitude();

            LatLng my = new LatLng(latitude, longitude);

            return my;
        }
    }catch(Exception e){
        Log.e("Erro", "(pegaMyLocation) : "+e);
    }


    return null;
}
  • "takes" the map, enables Mylocation, calls a method, responsible for picking up the Location (remembering that in Androidmanifest must have GPS permission), the method returns a Latlng object, which is passed as parameter to the mobile methodCamera... answered?

  • 1

    Tapping the eye, it seems to me that this code falls into the same question code problem. The method getLastKnownLocation() can return null and break the rest of the code, in case when myPosition is passed to the method that moves the camera.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.