onMapReady получить нулевой LatLng

голоса
0

У меня есть проблема с onMapReady . Когда я передать адрес , как это:

LatLng myAddressCoordinates = getLocationFromAddress(Piazza Ferretto Mestre);

Обе карты и маркер отлично работает, но когда я передать адрес чтения из TextView:

LatLng myAddressCoordinates = getLocationFromAddress(TVStringa.getText().toString());

Я бросаю это исключение:

java.lang.IllegalArgumentException: latlng cannot be null - a position is required.
        at com.google.android.gms.maps.model.MarkerOptions.position(Unknown Source:6)
        at com.example.alex.alfa0.schedaIntervento.onMapReady(schedaIntervento.java:199)
        at com.google.android.gms.maps.zzaj.zza(Unknown Source:7)
        at com.google.android.gms.maps.internal.zzaq.onTransact(Unknown Source:38)
        at android.os.Binder.transact(Binder.java:627)
        at gl.b(:com.google.android.gms.DynamiteModulesB@11580470:20)
        at com.google.android.gms.maps.internal.bf.a(:com.google.android.gms.DynamiteModulesB@11580470:5)
        at com.google.maps.api.android.lib6.impl.bc.run(:com.google.android.gms.DynamiteModulesB@11580470:5)
        at android.os.Handler.handleCallback(Handler.java:790)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6494)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

Строка 199:

mapView.addMarker(new MarkerOptions().position(myAddressCoordinates).title(Indirizzo));

Мой getLocationFromAddress метод:

public LatLng getLocationFromAddress(String strAddress) {
        /**
         * A class for handling geocoding and reverse geocoding.
         * Geocoding is the process of transforming a street address or other description of a location into a (latitude, longitude) coordinate.
         * Reverse geocoding is the process of transforming a (latitude, longitude) coordinate into a (partial) address.
         * The amount of detail in a reverse geocoded location description may vary,
         * for example one might contain the full street address of the closest building,
         * while another might contain only a city name and postal code.
         *
         * See more at: https://developer.android.com/reference/android/location/Geocoder.html
         */
        Geocoder coder = new Geocoder(this);

        //A list because of getFromLocationName will return a list of address depending on how many result I want
        List<Address> address;
        LatLng p1 = null;

        try {
            /**
             * List<Address> getFromLocationName (String locationName, int maxResults)             *
             * | locationName | String: |           a user-supplied description of a location                      |
             * | maxResults   |   int:  |max number of results to return. Smaller numbers (1 to 5) are recommended |
             * See more at: https://developer.android.com/reference/android/location/Geocoder.html
             */
            address = coder.getFromLocationName(strAddress, 2);
            if (address == null) {
                return null;
            }            //I take just the first result even if I've got list of 5 different LAT;LNG results
            Address location = address.get(0);
            location.getLatitude();
            location.getLongitude();
            p1 = new LatLng(location.getLatitude(), location.getLongitude());
            return p1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return p1;
    }

Полный код класса:

public class schedaIntervento extends AppCompatActivity implements OnMapReadyCallback {
    TextView TVNome, TVID, TVNomeP, TVCognome, TVVia, TVNumero, TVCitta, TVCap, TVChiamata, TVOperatore, TVCodice, TVData, TVStringa;
    String Nomee, Indirizzo;
    GoogleMap mapView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scheda_intervento);
        TVNome = findViewById(R.id.TVNome);
        TVID =  findViewById(R.id.TVID);
        TVNomeP = findViewById(R.id.TVNomeP);
        TVCognome = findViewById(R.id.TVCognome);
        TVVia=findViewById(R.id.TVVia);
        TVNumero = findViewById(R.id.TVNumero);
        TVCitta = findViewById(R.id.TVCitta);
        TVCap = findViewById(R.id.TVCap);
        TVChiamata = findViewById(R.id.TVChiamata);
        TVOperatore = findViewById(R.id.TVOperatore);
        TVCodice = findViewById(R.id.TVCodice);
        TVData = findViewById(R.id.TVData);
        TVStringa = findViewById(R.id.TVStringa);
        Nomee = getUsername();
        String url = myurlforapi;
        getJSON(url);
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.mapView);
        mapFragment.getMapAsync( this);
    }

    private String getUsername() {
        Intent i = getIntent();
        String j = i.getStringExtra(Username);
        TVNome.setText(j);
        return j;
    }

    private void getJSON(final String urlWebService) {

        class GetJSON extends AsyncTask<Void, Void, String> {
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            }
            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                try {
                    loadIntoTextView(s);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected String doInBackground(Void... voids) {
                try {
                    URL url = new URL(urlWebService);
                    HttpURLConnection con = (HttpURLConnection) url.openConnection();
                    con.setRequestMethod(POST);
                    con.setDoInput(true);
                    con.setDoOutput(true);
                    Uri.Builder builder = new Uri.Builder()
                            .appendQueryParameter(Username, Nomee);
                    String query = builder.build().getEncodedQuery();
                    OutputStream os = con.getOutputStream();
                    BufferedWriter writer = new BufferedWriter(
                            new OutputStreamWriter(os, UTF-8));
                    writer.write(query);
                    writer.flush();
                    writer.close();
                    os.close();
                    con.connect();

                    StringBuilder sb = new StringBuilder();
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
                    String json;

                    while ((json = bufferedReader.readLine()) != null) {
                        sb.append(json + \n);
                    }
                    return sb.toString().trim();
                } catch (Exception e) {
                    return null;
                }
            }
        }
        GetJSON getJSON = new GetJSON();
        getJSON.execute();
    }

    private void loadIntoTextView(String json) throws JSONException {
        JSONArray jsonArray = new JSONArray(json);
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject obj = jsonArray.getJSONObject(i);
            TVNomeP.setText(obj.getString(Nome));
            TVCognome.setText(obj.getString(Cognome));
            TVVia.setText(obj.getString(Via));
            TVNumero.setText(obj.getString(Numero));
            TVCitta.setText(obj.getString(Citta));
            TVCap.setText(obj.getString(CAP));
            TVChiamata.setText(obj.getString(Motivo_chiamata));
            TVOperatore.setText(obj.getString(Operatore));
            TVCodice.setText(obj.getString(codice));
            TVData.setText(obj.getString(Data_di_nascita));
            Indirizzo = Via  + TVVia.getText().toString() +   + TVNumero.getText().toString() +   + TVCitta.getText().toString();
            TVStringa.setText(Indirizzo);
        }
    }


    public LatLng getLocationFromAddress(String strAddress) {
        /**
         * A class for handling geocoding and reverse geocoding.
         * Geocoding is the process of transforming a street address or other description of a location into a (latitude, longitude) coordinate.
         * Reverse geocoding is the process of transforming a (latitude, longitude) coordinate into a (partial) address.
         * The amount of detail in a reverse geocoded location description may vary,
         * for example one might contain the full street address of the closest building,
         * while another might contain only a city name and postal code.
         *
         * See more at: https://developer.android.com/reference/android/location/Geocoder.html
         */
        Geocoder coder = new Geocoder(this);

        //A list because of getFromLocationName will return a list of address depending on how many result I want
        List<Address> address;
        LatLng p1 = null;

        try {
            /**
             * List<Address> getFromLocationName (String locationName, int maxResults)             *
             * | locationName | String: |           a user-supplied description of a location                      |
             * | maxResults   |   int:  |max number of results to return. Smaller numbers (1 to 5) are recommended |
             * See more at: https://developer.android.com/reference/android/location/Geocoder.html
             */
            address = coder.getFromLocationName(strAddress, 2);
            if (address == null) {
                return null;
            }            //I take just the first result even if I've got list of 5 different LAT;LNG results
            Address location = address.get(0);
            location.getLatitude();
            location.getLongitude();
            p1 = new LatLng(location.getLatitude(), location.getLongitude());
            return p1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return p1;
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        this.finish();
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        this.mapView = googleMap;
        /*LatLng sydney = new LatLng(-33.852, 151.211);
        googleMap.addMarker(new MarkerOptions().position(sydney)
                .title(Marker in Sydney));
        googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));*/


        LatLng myAddressCoordinates = getLocationFromAddress(TVStringa.getText().toString());
        //LatLng myAddressCoordinates = getLocationFromAddress(Piazza Ferretto Mestre);
        mapView.addMarker(new MarkerOptions().position(myAddressCoordinates).title(Indirizzo));
        mapView.moveCamera(CameraUpdateFactory.newLatLngZoom(myAddressCoordinates, 16));
    }
}
Задан 11/04/2018 в 15:52
источник пользователем
На других языках...                            


1 ответов

голоса
0

Помимо обработки ошибок вообще, вам необходимо согласовать нагрузку на карту и JSON нагрузки такие, что, когда JSON завершения загрузки карта доступна для использования.

Это лишь один из способов решить, что условие гонки.

Удалить (перемещая его onMapReady) вызов getJSON(url)с вашегоonCreate

Измените свой , onMapReadyчтобы начать загрузку JSON (и удалить getLocationFromAddressвызов и карту ОПС):

public void onMapReady(GoogleMap googleMap) {
   this.mapView = googleMap;
   getJSON(url);
 }

Обновление postExecuteиз ваших AsyncTask:

protected void onPostExecute(String s) {
    super.onPostExecute(s);
    try {
        loadIntoTextView(s);

        // MOVED FROM onMapReady
        LatLng myAddressCoordinates = getLocationFromAddress(TVStringa.getText().toString());
          //LatLng myAddressCoordinates = getLocationFromAddress("Piazza Ferretto Mestre");
          mapView.addMarker(new MarkerOptions().position(myAddressCoordinates).title(Indirizzo));
          mapView.moveCamera(CameraUpdateFactory.newLatLngZoom(myAddressCoordinates, 16));

    } catch (JSONException e) {
        e.printStackTrace();
    }
}
Ответил 11/04/2018 в 16:25
источник пользователем

Cookies help us deliver our services. By using our services, you agree to our use of cookies. Learn more