Auto zoom

2

I do not know this function is native to the Google Maps API but I can not start the zoom map in my location, 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?

    
asked by anonymous 21.11.2015 / 20:46

1 answer

3

If you just want to zoom in (your map is already in the correct coordinates), you can do:

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

However, the moveCamera(update) method makes a sudden 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 zooms in on 1 .

CameraUpdateFactory.zoomOut();

- > This method zooms to 1.

CameraUpdateFactory.zoomBy(10);

- > This method zooms in or out of the map, depending on the value reported

EDIT: getting location

To get the latest location efficiently you should use FusedLocationApi , but to use it you must create and connect to 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 object created, we need to make the connection and then disconnect, which according to the google documentation should be done onStart () and onStop (), respectively:

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

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

You also need to have your activity or fragment implement GoogleApiClient.ConnectionCallbacks and GoogleApiClient.OnConnectionFailedListener , to know when the connection was successful or interrupted and to see if it failed, respectively:

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

Once you've done this, you'll 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 everything happens as expected, the onConnected(Bundle bundle) method will be called and in it you should get the location, like this:

    @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 the last known location.

    
21.11.2015 / 22:10