Map show current location

7

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

I created this code that was apparently working, but sometimes it can not pick up 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)
    
asked by anonymous 03.02.2015 / 02:04

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);
    
19.10.2015 / 02:31
0

Dude, try this here:

@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;
}
    
03.02.2015 / 03:49
0

This is how I do it

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 map the map, if necessary

    
14.01.2018 / 05:02