1

我对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));
    }
}
4

1 回答 1

0

除了一般错误处理之外,您还需要协调地图加载和 JSON 加载,以便在 JSON 加载完成时地图可供使用。

这只是解决这种竞争条件的一种方法。

从您onMapReadygetJSON(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();
    }
}
于 2018-04-11T16:25:51.320 回答