J'essaye de créer une application Android, où je récupère un tableau JSON à partir du service Web. Dans mon tableau JSON, j'ai une liste d'endroits et à partir de là, je dois tracer ces endroits dans mes google maps sous Android. Ici, je suis capable de récupérer chaque place, mais je ne peux tracer que la dernière place dans mon tableau JSON. J'ai besoin de tracer tous les emplacements du tableau JSON dans ma carte google.

Code:

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

public GoogleMap mMap;
public String TAG = MapsActivity.class.getSimpleName();
public ProgressDialog pDialog;
public String cityName;
public static String url = "http://lawgo.in/lawgo/city?format=json";


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
    new GetAddress().execute();
}

public void onMapSearch(View view) {

    EditText locationSearch = (EditText) findViewById(R.id.SearchLocation);
    String location = locationSearch.getText().toString();
    List<Address> addressList = null;

    if (location != null || !location.equals("")) {
        Geocoder geocoder = new Geocoder(this);
        try {
            addressList = geocoder.getFromLocationName(location, 1);

        } catch (IOException e) {
            e.printStackTrace();
        }
        Address address = addressList.get(0);
        LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
        mMap.addMarker(new MarkerOptions().position(latLng).title(address.getFeatureName()));
        mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 13));
    }
}


@Override
public void onMapReady(GoogleMap googleMap) {

    mMap = googleMap;
    mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {
        mMap.setMyLocationEnabled(true);
    }
    mMap.getUiSettings().setCompassEnabled(true);
    mMap.getUiSettings().setZoomControlsEnabled(true);
    mMap.getUiSettings().setMyLocationButtonEnabled(true);
    Toast.makeText(this, "Press the top right button for your location", Toast.LENGTH_LONG).show();
}

public class GetAddress extends AsyncTask<Void, String, String> {

    @Override
    public void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(MapsActivity.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();

    }

    @Override
    public String doInBackground(Void... params) {

        HttpHandler sh = new HttpHandler();

        //call the function where Json string is retrieved
        String jsonStr = sh.makeServiceCall(url);

        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);

                // getting JSON ARRAY node
                JSONArray city = jsonObj.getJSONArray("city");   // call JSON

                for (int i = 0; i < city.length(); i++) {
                    JSONObject c = city.getJSONObject(i);

                    cityName = c.getString("cityname");
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return cityName;
    }

    @Override
    public void onPostExecute(String result){

        super.onPostExecute(result);
        // Dismiss the progress dialog

        if(pDialog.isShowing())
            pDialog.dismiss();

        List<Address> addressList = null;

        if (result != null || !result.equals("")) {
            Geocoder geocoder = new Geocoder(MapsActivity.this);
            try {
                addressList = geocoder.getFromLocationName(result, 1);

            } catch (IOException e) {
                e.printStackTrace();
            }
            Address address = addressList.get(0);
            LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
            mMap.addMarker(new MarkerOptions().position(latLng).title(address.getFeatureName()));
            mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,13));
        }
    }
}}

Veuillez aider! Je vous remercie!

-1
user7013119 16 janv. 2017 à 09:15

2 réponses

Meilleure réponse

Dans onPostExecute, vous n'itérez pas le addressList. Essayez ci-dessous le code

for (int i = 0; i < addressList.size(); i++) {
        Address address = addressList.get(i);
        LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
        mMap.addMarker(new MarkerOptions().position(latLng).title(address.getFeatureName()));
        mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,13));
}

UPDATE : pour renvoyer tous les noms de villes de doInBackground, vous pouvez utiliser un ArrayList de type String et le renvoyer depuis doInBackground.

Ici, je poste juste les codes pertinents. Voyez si cela résout votre problème.

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

public GoogleMap mMap;
public String TAG = MapsActivity.class.getSimpleName();
public ProgressDialog pDialog;
public static String url = "http://lawgo.in/lawgo/city?format=json";
public ArrayList<String> cityName;


public class GetAddress extends AsyncTask<Void, String, ArrayList<String>> {

    @Override
    public void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(MapsActivity.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();

    }

    @Override
    public String doInBackground(Void... params) {

        HttpHandler sh = new HttpHandler();

        //call the function where Json string is retrieved
        String jsonStr = sh.makeServiceCall(url);

        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);

                // getting JSON ARRAY node
                JSONArray city = jsonObj.getJSONArray("city");   // call JSON

                for (int i = 0; i < city.length(); i++) {
                    JSONObject c = city.getJSONObject(i);

                    cityName.add(c.getString("cityname"));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return cityName;
    }

    @Override
    public void onPostExecute(String result){

        super.onPostExecute(result);
        // Dismiss the progress dialog

        if(pDialog.isShowing())
            pDialog.dismiss();

        List<Address> addressList = null;

        if (result != null || result.size() > 0) {
          for (String cityTitle : result) {
            Geocoder geocoder = new Geocoder(MapsActivity.this);
            try {
                addressList = geocoder.getFromLocationName(cityTitle, 1);
            } catch (IOException e) {
                e.printStackTrace();
            }
          }

          for (int i = 0; i < addressList.size(); i++) {
                  Address address = addressList.get(i);
                  LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
                  mMap.addMarker(new MarkerOptions().position(latLng).title(address.getFeatureName()));
                  mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,13));
          }
        }
    }
}}
0
fluffyBatman 16 janv. 2017 à 06:52

Parcourez le addressList pour obtenir tous les lieux sur la carte.

for (Address address: addressList
             ) {
            LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
            mMap.addMarker(new MarkerOptions().position(latLng).title(address.getFeatureName()));
            mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,13));
        }

MISE À JOUR:

 private List<String> cityNameList= new ArrayList<>();  //global variable
//change the parameter of AsyncTask to change the return type of doInBackground and parameter of postExecute
    public class GetAddress extends AsyncTask<Void, String, List<String>> {

 @Override
        public List<String> doInBackground(Void... params) {

            HttpHandler sh = new HttpHandler();

            //call the function where Json string is retrieved
            String jsonStr = sh.makeServiceCall(url);

            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);

                    // getting JSON ARRAY node
                    JSONArray city = jsonObj.getJSONArray("city");   // call JSON

                    for (int i = 0; i < city.length(); i++) {
                        JSONObject c = city.getJSONObject(i);

                        cityName = c.getString("cityname");
                        cityNameList.add(cityName);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            return cityNameList;
        }

        @Override
        public void onPostExecute(List<String> resultList){

            super.onPostExecute(resultList);
    ....
    }
0
Sadiq Md Asif 16 janv. 2017 à 06:54