Automatic zoom

Asked

Viewed 129 times

2

I don’t know this function is native to the Google Maps API but I’m not able to zoom in on my location map, follow my code.

public class MainActivity extends FragmentActivity {

    GoogleMap mGoogleMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);

        // Obtendo referência a SupportMapFragment
        SupportMapFragment fragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);

        // Criando GoogleMap de SupportMapFragment
        mGoogleMap = fragment.getMap();

        // Ativando o botão MyLocation para o mapa do Google

        mGoogleMap.setMyLocationEnabled(true);

        // Definir ouvinte OnClickEvent para o GoogleMap
        mGoogleMap.setOnMapClickListener(new OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latlng) {
                addMarker(latlng);
                sendToServer(latlng);
            }
        });



        //  Locais de partida recuperar tarefa
        new RetrieveTask().execute();
    }


    //Adicionando marcador no GoogleMaps
    private void addMarker(LatLng latlng) {
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(latlng);
        markerOptions.title(latlng.latitude + "," + latlng.longitude);
        mGoogleMap.addMarker(markerOptions);
    }

    // Invocando discussão de fundo para armazenar o local tocado em Remover servidor MySQL
    private void sendToServer(LatLng latlng) {
        new SaveTask().execute(latlng);
    }
    // Segmento de segundo plano para salvar o local em remover servidor MySQL
    private class SaveTask extends AsyncTask<LatLng, Void, Void> {
        @Override
        protected Void doInBackground(LatLng... params) {
            String lat = Double.toString(params[0].latitude);
            String lng = Double.toString(params[0].longitude);
            String strUrl = "http://t4web.hospedagemdesites.ws/alarme/save.php";
            URL url = null;
            try {
                url = new URL(strUrl);

                HttpURLConnection connection = (HttpURLConnection) url
                        .openConnection();
                connection.setRequestMethod("POST");
                connection.setDoOutput(true);
                OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
                        connection.getOutputStream());

                outputStreamWriter.write("lat=" + lat + "&lng="+lng);
                outputStreamWriter.flush();
                outputStreamWriter.close();

                InputStream iStream = connection.getInputStream();
                BufferedReader reader = new BufferedReader(new
                        InputStreamReader(iStream));

                StringBuffer sb = new StringBuffer();

                String line = "";

                while( (line = reader.readLine()) != null){
                    sb.append(line);

                }

                // Atualizar no momento que salvar uma nova posição \o/

                new RetrieveTask().execute();
                reader.close();
                iStream.close();

                //final do while é aqui

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;

        }

    }



    // Tarefa de fundo para recuperar locais de servidor mysql remoto
    private class RetrieveTask extends AsyncTask<Void, Void, String>{

        @Override
        protected String doInBackground(Void... params) {
            String strUrl = "http://t4web.hospedagemdesites.ws/alarme/retrieve.php";
            URL url = null;
            StringBuffer sb = new StringBuffer();
            try {
                url = new URL(strUrl);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.connect();
                InputStream iStream = connection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(iStream));

                String line = "";
                while( (line = reader.readLine()) != null){
                    sb.append(line);
                }

                reader.close();
                iStream.close();

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return sb.toString();
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            new ParserTask().execute(result);
        }
    }



    // Discussão de fundo para analisar os dados JSON recuperados do servidor MySQL
    private class ParserTask extends AsyncTask<String, Void, List<HashMap<String, String>>>{
        @Override
        protected List<HashMap<String,String>> doInBackground(String... params) {
            MarkerJSONParser markerParser = new MarkerJSONParser();
            JSONObject json = null;
            try {
                json = new JSONObject(params[0]);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            List<HashMap<String, String>> markersList = markerParser.parse(json);
            return markersList;
        }



        @Override
        protected void onPostExecute(List<HashMap<String, String>> result) {
            for(int i=0; i<result.size();i++){
                HashMap<String, String> marker = result.get(i);
                LatLng latlng = new LatLng(Double.parseDouble(marker.get("lat")), Double.parseDouble(marker.get("lng")));
                addMarker(latlng);
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflar o menu ; este adiciona itens à barra de ação se ela estiver presente
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}

Does anyone have any suggestions?

  • The map doesn’t even start showing your location or already shows and you just want it to start zooming in at that location?

  • Yes, he should zoom in on my location as soon as he opens the map.

  • Your code does not show how you get user coordinates. Using only setMyLocationEnabled you get a mark on the map but it doesn’t give you that information.

1 answer

3


If you simply want to set a zoom (your map already being at the correct coordinates), you can do:

CameraUpdate update = CameraUpdateFactory.zoomTo(13); // valor do zoom
mGoogleMap.moveCamera(update);

However, the method moveCamera(update) makes a sharp change in the camera, if you want it to increase in an animated way, you can use the:

mGoogleMap.animateCamera(update);

Other:

Other interesting methods to handle the zoom, are:

CameraUpdateFactory.zoomIn();

-> This method increases the zoom by 1.

CameraUpdateFactory.zoomOut();

-> This method decreases the zoom by 1.

CameraUpdateFactory.zoomBy(10);

-> This method increases or decreases the map zoom, depending on the given value

EDIT: getting the location

To get the last location efficiently you must use the FusedLocationApi, however, to use it you need to create and connect to a GoogleApiClient. So come on:

Creating a GoogleApiClient:

private GoogleApiClient mGoogleApiClient;
...
// Isso é feito no onCreate() da activity ou fragment
mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API) // Informamos a API de localização
                .build();

With the created object, we need to make the connection and then disconnect, which according to the google documentation should be done in onStart() and onStop(), respectively:

@Override
protected void onStart() {
    super.onStart();
    mGoogleApiClient.connect();
}

@Override
protected void onStop() {
    mGoogleApiClient.disconnect();
    super.onStop();
}

You also need to get your Activity or Fragment to implement GoogleApiClient.ConnectionCallbacks and GoogleApiClient.OnConnectionFailedListener, for you to know when the connection was successful or interrupted and to know if there was failure, respectively:

implements  GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener ... {

Once done, you will have to implement the following three methods:

@Override
public void onConnected(Bundle bundle) {
    Log.d("DEBUG", "conectado ao google play services");
}

@Override
public void onConnectionSuspended(int cause) {
    Log.d("DEBUG", "conexão interrompida");
}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    Log.d("DEBUG", "erro ao conectar: " + connectionResult);
}

If all goes as expected, the method onConnected(Bundle bundle) will be called and in it you must get the location, that way:

    @Override
    public void onConnected(Bundle bundle) {
Log.d("DEBUG", "conectado ao google play services");
        Location location = LocationServices.FusedLocationApi.getLastLocation(
            mGoogleApiClient);
        setMyLocation(location);
    }

    private void setMyLocation(Location location) {
        if (mGoogleMap != null && location != null) {
            LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
            CameraUpdate update = CameraUpdateFactory.newLatLngZoom(latLng, 13); // seta o local e já o zoom
            mGoogleMap.animateCamera(update);
        }
    }

Remembering that the method: LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient) will return to last known location.

  • Os valores válidos para zoom são de 2 a 22 not true. The zoom starts at zero and maximum value depends on which position of the globe the camera points to, as the documentation.

  • @Androiderson, thank you. I will actualziar the reply!

  • He’s zooming in on a random location on the map and not my location, it could be my coordinates ?

  • That’s because you didn’t set your coordinates on the map. By your reply in the comments I thought you had already set and the problem was just the zoom. Soon I update the answer with this solution.

  • Thanks for the help Luiz.

  • I edited the answer, take a look!

Show 1 more comment

Browser other questions tagged

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