Search code examples
javaandroidandroid-fragmentsandroid-maps

Google map marker title android


i am trying to show all the nearest embassy from my current location. i am able to print all the embassies from my current location but the problem i am facing is that the title is same for all the embassies. for all the embassy is showing same title like in this pictures.enter image description here

All i want to do is to display in title the name of each embassy. currently only displaying "Embassy of Malta". The below is my code please suggest me where i am wrong. I am new to Android and this is my first project so please apologize in advance if my question is not strong enough. also many thanks in advance below is my code`public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {

GoogleMap mMap;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
private boolean flag = true;



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

    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        checkLocationPermission();
    }
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(map);
    mapFragment.getMapAsync(this);


}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

    //Initialize Google Play Services
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            buildGoogleApiClient();
            mMap.setMyLocationEnabled(true);
        }
    } else {
        buildGoogleApiClient();
        mMap.setMyLocationEnabled(true);
    }


}


protected synchronized void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
    mGoogleApiClient.connect();
}

@Override
public void onConnected(Bundle bundle) {

    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(1000);
    mLocationRequest.setFastestInterval(1000);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }

}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onLocationChanged(Location location) {

    mLastLocation = location;
    if (mCurrLocationMarker != null) {
        mCurrLocationMarker.remove();
    }

    //Place current location marker
    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
    MarkerOptions markerOptions = new MarkerOptions();
    markerOptions.position(latLng);
    markerOptions.title("Current Position");
    markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
    mCurrLocationMarker = mMap.addMarker(markerOptions);

    //move map camera
    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    mMap.animateCamera(CameraUpdateFactory.zoomTo(10));

    //stop location updates
    if (mGoogleApiClient != null) {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
    }
    new getEmbassyPoint().execute(new LatLng(location.getLatitude(), location.getLongitude()));


}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {

}

public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;

public boolean checkLocationPermission() {
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {

        // Asking user if explanation is needed
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.ACCESS_FINE_LOCATION)) {

            // Show an explanation to the user *asynchronously* -- don't block
            // this thread waiting for the user's response! After the user
            // sees the explanation, try again to request the permission.

            //Prompt the user once explanation has been shown
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    MY_PERMISSIONS_REQUEST_LOCATION);


        } else {
            // No explanation needed, we can request the permission.
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    MY_PERMISSIONS_REQUEST_LOCATION);
        }
        return false;
    } else {
        return true;
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_LOCATION: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted. Do the
                // contacts-related task you need to do.
                if (ContextCompat.checkSelfPermission(this,
                        Manifest.permission.ACCESS_FINE_LOCATION)
                        == PackageManager.PERMISSION_GRANTED) {

                    if (mGoogleApiClient == null) {
                        buildGoogleApiClient();
                    }
                    mMap.setMyLocationEnabled(true);
                }

            } else {

                // Permission denied, Disable the functionality that depends on this permission.
                Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
            }
            return;
        }

        // other 'case' lines to check for other permissions this app might request.
        // You can add here other case statements according to your requirement.
    }
}


class getEmbassyPoint extends AsyncTask<LatLng, String, ArrayList<LatLng>> {

    double x, y;
    String name;

    private LatLng myPoint;


    @Override
    protected ArrayList<LatLng> doInBackground(LatLng... params) {



        myPoint = params[0];

        String s = "https://maps.googleapis.com/maps/api/place/nearbysearch" + "/json?location=" + myPoint.latitude + "," + myPoint.longitude
                + "&radius=50000&types=embassy&name=ireland" + "&key=my api key";


        Log.i("app", s);



        try {
            URL url = new URL(s);
            BufferedReader r = new BufferedReader(new InputStreamReader(((HttpURLConnection) url.openConnection()).getInputStream()));
            JsonParser jp = new JsonParser();
            JsonElement jsonElement = jp.parse(r);
            JsonObject jsonObject = jsonElement.getAsJsonObject();
            JsonArray jsonArray = jsonObject.getAsJsonArray("results");


            List<LatLng> listt = new ArrayList<>();


            for (JsonElement element : jsonArray) {



                name = element.getAsJsonObject().get("name").getAsString();

                x = Double.valueOf(element.getAsJsonObject().get("geometry").getAsJsonObject().get("location").getAsJsonObject().get("lat").getAsString());
                y = Double.valueOf(element.getAsJsonObject().get("geometry").getAsJsonObject().get("location").getAsJsonObject().get("lng").getAsString());


                listt.add(new LatLng(x,y));

            }

            return  (ArrayList<LatLng>) listt;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    protected void onPostExecute(ArrayList<LatLng> latLngs) {
        super.onPostExecute(latLngs);


        for (LatLng latLng : latLngs){

            Log.i("app", "onPostExecute: lat: " + latLng.latitude);

            List<Marker> markers = new ArrayList<Marker>();

           Marker marker = mMap.addMarker(new MarkerOptions().position(latLng).title(name).icon(BitmapDescriptorFactory.fromResource(R.drawable.mosque)));

            markers.add(marker);
            MarkerOptions mp = new MarkerOptions();
            mp.title(name);

        }

    }

}

}`


Solution

  • in onPostExecute you are using an ArrayList of LatLng.

    Change that to an ArrayList of a custom object.

    In the custom object you want the LatLng and the title of the Marker.

    Your bug lies here:

    name = element.getAsJsonObject().get("name").getAsString();
    

    Your resetting the String name every single time you parse the JSONObject in your loop. You need to be storing this in your object

    Something like this should work: This won't compile but the changes are pretty easy, change everything from a ArrayList of LatLng to an arrayList of CustomObject

    class getEmbassyPoint extends AsyncTask<LatLng, String, ArrayList<CustomObject>> {
    
        double x, y;
        String name;
    
        private LatLng myPoint;
    
    
        @Override
        protected ArrayList<CustomObject> doInBackground(LatLng... params) {
    
    
    
            myPoint = params[0];
    
            String s = "https://maps.googleapis.com/maps/api/place/nearbysearch" + "/json?location=" + myPoint.latitude + "," + myPoint.longitude
                    + "&radius=50000&types=embassy&name=ireland" + "&key=my api key";
    
    
    
            try {
                URL url = new URL(s);
                BufferedReader r = new BufferedReader(new InputStreamReader(((HttpURLConnection) url.openConnection()).getInputStream()));
                JsonParser jp = new JsonParser();
                JsonElement jsonElement = jp.parse(r);
                JsonObject jsonObject = jsonElement.getAsJsonObject();
                JsonArray jsonArray = jsonObject.getAsJsonArray("results");
    
    
                List<CustomObject> listt = new ArrayList<>();
    
    
                for (JsonElement element : jsonArray) {
    
    
    
                    name = element.getAsJsonObject().get("name").getAsString();
    
                    x = Double.valueOf(element.getAsJsonObject().get("geometry").getAsJsonObject().get("location").getAsJsonObject().get("lat").getAsString());
                    y = Double.valueOf(element.getAsJsonObject().get("geometry").getAsJsonObject().get("location").getAsJsonObject().get("lng").getAsString());
    
                    CustomObject customObject = new CustomObject;
                    customObject.title = element.getAsJsonObject().get("name").getAsString();
                    customObject.latLng = new LatLng(x,y);
                    listt.add(customObject);
    
                }
    
                return  (ArrayList<CustomObject>) listt;
    
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
    
        @Override
        protected void onPostExecute(ArrayList<CustomObject> latLngs) {
            super.onPostExecute(latLngs);
    
            List<Marker> markers = new ArrayList<Marker>();
    
            for (CustomObject latLng : latLngs){
    
                Marker marker = mMap.addMarker(new MarkerOptions().position(latLng.latLng).title(latLng.title).icon(BitmapDescriptorFactory.fromResource(R.drawable.mosque)));
                markers.add(marker);
                MarkerOptions mp = new MarkerOptions();
                mp.title(latLng.title);
    
            }
    
        }
    
    }
    

    Your custom object:

    private class CustomObject {
        public LatLng latLng;
        public String title;
    }