7

Gostaria de saber como fazer para que o mapa mostrasse a localização atual do usuário.

Criei este código que aparentemente estava funcionando, só que algumas vezes ele não consegue pegar o local e a aplicação da erro.

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)
2
  • E qual é o erro? Edite a sua pergunta incluindo essa informação. Commented 3/02/2015 às 1:08
  • 1
    Editei agora!!!
    – Mantir
    Commented 3/02/2015 às 1:23

3 Respostas 3

2

Utilizei o código abaixo:

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));
        }
    }
};

Então set no seu mapa:

mMap.setOnMyLocationChangeListener(myLocationChangeListener);
0

Cara, tente isso aqui:

@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;
}
2
  • "pega" o mapa, habilita MyLocation, chama um método, responsável por pegar a Localização (lembrando que no AndroidManifest deve ter a permissão de GPS), o método retorna um objeto LatLng, que é passada como parâmetro para o método moveCamera... respondido? Commented 3/02/2015 às 2:55
  • 1
    Batendo o olho, me parece que esse código cai no mesmo problema do código da pergunta. O método getLastKnownLocation() pode retornar null e quebrar o restante do código, no caso quando myPosition é passada para o método que movimenta a câmera.
    – Piovezan
    Commented 19/10/2015 às 3:55
0

É assim que eu faço

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;
}

Esse código também mostra como eu seto o mapa, caso seja necessário

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .