0

Estoy queriendo desarrollar una app que despliegue un mapa con un Floating Action Button el cual permita al usuario agregar marcadores en el mapa según un intent de Places.

Me encuentro actualmente con una falla en el mapa al salir del intent de busqueda de Places dado que no me permite agregar el marcador porque la referencia al map se torna null.

Probé hacerlo mediante una interfaz pero para que llegue a los mismos resultados de null reference cuando tengo que agregar el marker en myMap.

Aca la actividad

public class MainActivity extends AppCompatActivity {

private static final int AUTOCOMPLETE_REQUEST_CODE = 1;
private FloatingActionButton fab;
private LatLng nueva_pos;
private String nombre_marc;

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

    Places.initialize(getApplicationContext(), "KEY");

    fab = findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            onSearchCalled();
        }
    });

    getSupportFragmentManager().beginTransaction()
            .add(R.id.container, new MapFragment(), "mapFragment")
            .commit();

}

public void onSearchCalled() {
    // Set the fields to specify which types of place data to return.
    List<Place.Field> fields = Arrays.asList(Place.Field.ID, Place.Field.NAME, Place.Field.ADDRESS, Place.Field.LAT_LNG);
    // Start the autocomplete intent.
    Intent intent = new Autocomplete.IntentBuilder(
            AutocompleteActivityMode.FULLSCREEN, fields).setCountry("AR") //Argentina
            .build(this);
    startActivityForResult(intent, AUTOCOMPLETE_REQUEST_CODE);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == AUTOCOMPLETE_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {
            Place place = Autocomplete.getPlaceFromIntent(data);

            //añadir marcador en nueva ubicación
            nueva_pos = place.getLatLng();
            nombre_marc = place.getName();
            MapFragment.getInstance().NuevoMarcador(nueva_pos,nombre_marc);
            Toast.makeText(MainActivity.this, "ID: " + place.getId() + "address:" + place.getAddress() + "Name:" + place.getName() + " latlong: " + place.getLatLng(), Toast.LENGTH_LONG).show();
            // do query with address

        } else if (resultCode == AutocompleteActivity.RESULT_ERROR) {
            // TODO: Handle the error.
            Status status = Autocomplete.getStatusFromIntent(data);
            Toast.makeText(MainActivity.this, "Error: " + "Ha ocurrido un error", Toast.LENGTH_LONG).show();
        }
    }
}
}

Aca el fragmento

Probé agregando un metodo en el OnResume que haga la llamada al onMapReady nuevamente para que se actualice la instancia del myMap pero no tuve resultados.

    public class MapFragment extends SupportMapFragment implements OnMapReadyCallback {

private GoogleMap myMap;
private static final String URL = "https://www.googleapis.com/geolocation/v1/geolocate?key=key";
private double longitud, latitud;

public static MapFragment getInstance() {
    return new MapFragment();
}

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View rootView = super.onCreateView(inflater, container, savedInstanceState);
    getMapAsync(this);
    return rootView;
}

@Override
public void onMapReady(GoogleMap googleMap) {
    myMap = googleMap;

    final JSONObject jsonObject = new JSONObject();

    try{

        jsonObject.put("homeMobileCountryCode","54")
                .put("homeMobileNetworkCode", "070")
                .put("radioType", "gsm")
                .put("carrier","Movistar")
                .put("considerIp", "true");

    }catch (JSONException e){
        e.printStackTrace();
    }

    RequestQueue queue = Volley.newRequestQueue(getContext());

    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, URL, jsonObject, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            try{

                JSONObject jsonCoord = response.getJSONObject("location");

                latitud = Double.parseDouble(jsonCoord.getString("lat"));
                longitud = Double.parseDouble(jsonCoord.getString("lng"));
                LatLng posicion = new LatLng(latitud, longitud);
                myMap.addMarker(new MarkerOptions().position(posicion).title("You're here!").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_VIOLET)));
                myMap.moveCamera(CameraUpdateFactory.newLatLng(posicion));
                Toast.makeText(getContext(), "Latitud: " + latitud + "\n" + "Longitud: " + longitud, Toast.LENGTH_LONG).show();

            }catch (JSONException e){
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(getContext(), "Ocurrió un error", Toast.LENGTH_SHORT).show();
        }
    });

    queue.add(jsonObjectRequest);
}

private void setupMapIfNeeded() {
    if (myMap == null) {
        this.getMapAsync(this);
    }
}

@Override
public void onResume() {
    super.onResume();
    setupMapIfNeeded();

}

public void NuevoMarcador(LatLng pos, String nombre_lugar) {
    setupMapIfNeeded();
    myMap.addMarker(new MarkerOptions().position(pos).title(nombre_lugar).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
}
}

1 respuesta 1

0

Para que la instancia del mapa y sus elementos tengan un valor diferente de null, el mapa debe estar cargado y esto se define al llamarse el método:

@Override
public void onMapReady(GoogleMap googleMap) {
    myMap = googleMap;
    ...
    ...
}

Desde el Fragment podrías llamar al intent.

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.