How to make Mapbox Marker clickable and get their properties? - android

I have the main activity where i load all my markers from the database into a List and then i add them in my map.
public void onMapReady(#NonNull final MapboxMap mapboxMap) {
MainActivity.this.mapboxMap = mapboxMap;
StringRequest request = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
List<Feature> symbolLayerIconFeatureList = new ArrayList<>();
for(int i = 0; i < jsonArray.length(); i++){
JSONObject crag = jsonArray.getJSONObject(i);
String nome = crag.getString("nome");
String tipo = crag.getString("tipo");
Double lng = crag.getDouble("longitudine");
Double lat = crag.getDouble("latitudine");
symbolLayerIconFeatureList.add(Feature.fromGeometry(Point.fromLngLat(lng,lat)));
symbolLayerIconFeatureList.get(i).addStringProperty("NAME_PROPERTY_KEY", nome);
symbolLayerIconFeatureList.get(i).addStringProperty("TYPE_KEY", tipo);
}
mapboxMap.setStyle(new Style.Builder().fromUri("mapbox://styles/mapbox/streets-v11")
.withSource(new GeoJsonSource(SOURCE_ID,
FeatureCollection.fromFeatures(symbolLayerIconFeatureList)))
.withLayer(new SymbolLayer(LAYER_ID, SOURCE_ID)
.withProperties(
iconImage(get("TYPE_KEY")),
iconAllowOverlap(true),
iconIgnorePlacement(true),
textOffset(new Float[]{0f,-2.5f}),
textIgnorePlacement(true),
textAllowOverlap(true),
textField(get("NAME_PROPERTY_KEY"))
)
), new Style.OnStyleLoaded() {
#Override
public void onStyleLoaded(#NonNull Style style) {
mapboxMap.addOnMapClickListener(MainActivity.this);
mapboxMap.getUiSettings().setLogoEnabled(false);
mapboxMap.getUiSettings().setAttributionEnabled(false);
enableLocationComponent(style);
}
});
} catch (JSONException e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mQueue.add(request);
mapView.addOnStyleImageMissingListener(new MapView.OnStyleImageMissingListener() {
#Override
public void onStyleImageMissing(#NonNull String id) {
if(id.equals("Falesia")){
addImage(id, R.drawable.icona_falesia);
} else{
addImage(id, R.drawable.icon_gym);
}
}
});
}
I can't figure how to make them clickable
I saw the documentation and the example and maybe i have to implement onMapClick method, but i don't know what put in it.
Does anyone know how to implement it or other way to make them clickable?
Thank you.

You can add a map click listener in your onMapReady-callback. In your onMapClick-method you set up a query at the selected point to see if there are any features in the symbollayer at that location. Then you get a list of features in that point that you can use. Here's a very condensed version of what I'm using:
private void handleMapClick(LatLng point){
if (myMapboxMap != null){
final PointF screenPoint = myMapboxMap.getProjection().toScreenLocation(point);
List<Feature> features = myMapboxMap.queryRenderedFeatures(screenPoint, SYMBOL_LAYER_ID);
if (!features.isEmpty()) {
//do stuff with features in feature list
}
}
}

Related

how do I setText value when I on click button?

how do I setText value when I on click button?
now, I can get the value from my DB, but how can set text when I click the button?
private JsonArrayRequest getDataFromServer(int requestCount) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Load...");
final String DATA_URL = "https://aaa.ccc/eee.php";
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(DATA_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
parseData(response);
progressDialog.dismiss();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
}
});
return jsonArrayRequest;
}
private void loadTravelRule() {
requestQueue.add(getDataFromServer(requestCount));
requestCount++;
}
private void parseData(JSONArray array) {
for (int i = 0; i < array.length(); i++) {
TravelRuleModel travelRuleModel = new TravelRuleModel();
JSONObject json = null;
try {
json = array.getJSONObject(i);
String TAG_TravelRule = "TravelRule";
travelRuleModel.setTravelrule(json.getString(TAG_TravelRule));
} catch (JSONException e) {
e.printStackTrace();
}
travelRuleModels.add(travelRuleModel);
}
}
I can get json.getString(TAG_TravelRule) value, but I want to set value in here.
tips.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(MainActivity.this, R.style.BottomSheetDialogTheme);
View bottomSheetView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.tips, (LinearLayout)findViewById(R.id.bottomSheetContainer));
travel_rule = findViewById(R.id.travel_rule);
// Can I set value to R.id.travel_rule in R.layout.tips???
if it is can set value how can I do?
bottomSheetDialog.setContentView(bottomSheetView);
bottomSheetDialog.show();
}
});
I tried to used
rule = json.getString(TAG_TravelRule);
then
travel_rule.setText(rule);
but I got null
I suppose the textview is on the bottomSheetView xml so you have to reference that to find your textview
travel_rule = bottomSheetView.findViewById(R.id.travel_rule);

Fetch data using volley and display in Google Maps

This is my first time working with Google Maps in android. I was able to create a map displaying one marker. That was a good start for me. However, I would like to display multiple markers. To do these, I am fetching the locations from the database using volley. However, I am experiencing one problem, one that I have experienced before but I managed to have a work around then and now it has surfaced again in my current project i.e I like using Singletons in my application to store data as long as the application is in memory. My singleton for instance could hold an array list of objects and I can get the array list anywhere and any time in any activity/fragment. However, I need to populate the arraylist in my singleton before activity/fragment becomes active and access the arraylist of objects in onCreate/onCreateView but it seems the activity/fragment loads very fast and a reference to the arraylist of objects from the singleton is always null. In my current project:
This is the singleton class that handles all the locations
public class PointOfInterestLab {
private ArrayList<PointOfInterest> mPointOfInterests;
private static PointOfInterestLab sPointOfInterestLab;
private Context mAppContext;
private PointOfInterestLab(Context appContext){
mAppContext = appContext;
mPointOfInterests = new ArrayList<PointOfInterest>();
}
public static PointOfInterestLab get(Context c){
if(sPointOfInterestLab == null){
sPointOfInterestLab = new PointOfInterestLab(c.getApplicationContext());
}
return sPointOfInterestLab;
}
public ArrayList<PointOfInterest> getPointOfInterests(){
return mPointOfInterests;
}
public PointOfInterest getPointOfInterest(int id){
for(PointOfInterest pointOfInterest: mPointOfInterests){
if(pointOfInterest.getID() == id){
return pointOfInterest;
}
}
return null;
}
public void addPointOfInterest(PointOfInterest pointOfInterest){
mPointOfInterests.add(pointOfInterest);
}
public void clearPointOfInterests(){
mPointOfInterests.clear();
}
public void deletePointOfInterest(PointOfInterest pointOfInterest){
mPointOfInterests.remove(pointOfInterest);
}
}
In the fragment that I want to display the locations:
public class PointOfInterestMapFragment extends Fragment implements OnMapReadyCallback {
private static final String TAG = PointOfInterestMapFragment.class.getSimpleName();
private GoogleMap mGoogleMap;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
//get locations from server
getPOISFromDB();
}//end method onCreate
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle saveInstanceState){
View v = inflater.inflate(R.layout.fragment_poi_map, parent, false);
//obtain the support fragment and get notified when the map is ready
SupportMapFragment mapFragment = (SupportMapFragment)getChildFragmentManager()
.findFragmentById(R.id.map);
//pass fragment in getMapAsync handler
mapFragment.getMapAsync(this);
return v;
}//end method onCreateView
#Override
public void onMapReady(GoogleMap googleMap){
mGoogleMap = googleMap;
ArrayList<PointOfInterest> pointOfInterests;
pointOfInterests = PointOfInterestLab.get(getActivity())
.getPointOfInterests();
for(PointOfInterest pointOfInterest : pointOfInterests){
//add marker and move camera
/*LatLng location = new LatLng(pointOfInterest.getLocation().getLatitude()
, pointOfInterest.getLocation().getLongitude());
mGoogleMap.addMarker(new MarkerOptions()
.position(location)
.title(pointOfInterest.getName()));
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(location));*/
Log.d(TAG, pointOfInterest.getName());
}
/*This is just for debugging, it is returning a null object
Meaning by the time the array list of the singleton class
is being populated this has been called I guess*/
PointOfInterest pointOfInterest = PointOfInterestLab.get(getActivity()).getPointOfInterest(3);
LatLng location = new LatLng(pointOfInterest.getLocation().getLatitude(),pointOfInterest.getLocation().getLongitude());
mGoogleMap.addMarker(new MarkerOptions()
.position(location)
.title("location"));
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(location));
}
//Get locations from db
private void getPOISFromDB(){
// Tag used to cancel the request
String tag_string_req = "req_poi_list";
StringRequest strReq = new StringRequest(Request.Method.POST,
AppConfig.URL_POI_LIST, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Response: " + response);
try {
JSONObject jObj = new JSONObject(response);
JSONArray jsonArray = jObj.getJSONArray("pois");
PointOfInterestLab.get(getActivity()).clearPointOfInterests();
for(int i=0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
int id = jsonObject.getInt("poi_id");
String name = jsonObject.getString("name");
String summary = jsonObject.getString("summary");
double latitude = jsonObject.getDouble("latitude");
double longitude = jsonObject.getDouble("longitude");
Location location = new Location("dummyProvider");
location.setLatitude(latitude);
location.setLongitude(longitude);
PointOfInterest pointOfInterest = new PointOfInterest(id, name, summary
, location);
PointOfInterestLab.get(getActivity()).addPointOfInterest(pointOfInterest);
}
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Server error: " + error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
SQLiteHandler sqLiteHandler = new SQLiteHandler(getActivity());
User user = sqLiteHandler.getUserDetails();
params.put("user_id", user.getUserID());
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}//end method getPOISFromDB
}//end class
This is the part of the code that I am using to test for now. I am getting error PointOfInterest.getLocation()' on a null object reference on line LatLng location = new LatLng(pointOfInterest.getLocation().getLatitude(),pointOfInterest.getLocation().getLongitude());
/*This is just for debugging, it is returning a null object
Meaning by the time the array list of the singleton class
is being populated this has been called I guess*/
PointOfInterest pointOfInterest = PointOfInterestLab.get(getActivity()).getPointOfInterest(3);
LatLng location = new LatLng(pointOfInterest.getLocation().getLatitude(),pointOfInterest.getLocation().getLongitude());
mGoogleMap.addMarker(new MarkerOptions()
.position(location)
.title("location"));
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(location));
I have also tried calling the database api in the onCreate method of the hosting activity but doesn't seem to work
public class MainActivity extends AppCompatActivity {
......
#Override
public void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pedometer);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
User user = new User();
user.checkLogin(MainActivity.this);
tabLayout = (TabLayout)findViewById(R.id.tabs);
viewPager = (ViewPager)findViewById(R.id.viewpager);
viewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));
viewPager.setOffscreenPageLimit(2);
//runnable to get rid of bug
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
setTitle("Updates");
//get locations from db
getPOISFromDB();
}//end method onCreate
private class MyAdapter extends FragmentStatePagerAdapter {
private MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position)
{
switch (position){
case 0 :
return new FirstFragment();
case 1 :
eturn new SecondFragment();
case 2 :
return new PointOfInterestMapFragment();
}
return null;
}
#Override
public int getCount() {
return 3;
}
/**
* This method returns the title of the tab according to the position.
*/
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0 :
return getResources().getString(R.string.fragment_1);
case 1 :
return getResources().getString(R.string.fragment_2);
case 2 :
return getResources().getString(R.string.fragment_3);
}
return null;
}
}//end class MyAdapter
private void getPOISFromDB(){
// Tag used to cancel the request
String tag_string_req = "req_poi_list";
StringRequest strReq = new StringRequest(Request.Method.POST,
AppConfig.URL_POI_LIST, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Response: " + response);
try {
JSONObject jObj = new JSONObject(response);
JSONArray jsonArray = jObj.getJSONArray("pois");
PointOfInterestLab.get(AppController.getInstance()).clearPointOfInterests();
for(int i=0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
int id = jsonObject.getInt("poi_id");
String name = jsonObject.getString("name");
String summary = jsonObject.getString("summary");
double latitude = jsonObject.getDouble("latitude");
double longitude = jsonObject.getDouble("longitude");
Location location = new Location("dummyProvider");
location.setLatitude(latitude);
location.setLongitude(longitude);
PointOfInterest pointOfInterest = new PointOfInterest(id, name, summary
, location);
PointOfInterestLab.get(AppController.getInstance()).addPointOfInterest(pointOfInterest);
}
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Server error: " + error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
SQLiteHandler sqLiteHandler = new SQLiteHandler(AppController.getInstance());
User user = sqLiteHandler.getUserDetails();
params.put("user_id", user.getUserID());
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}//end method getPOISFromDB
}
How do I display the markers in onMapReady method i.e populate the singleton before the onMapReady method executes?
Thanks to #soham, I changed to initialize my adapter after the response from the api. Removed this line of code in onCreate in the MainActivity
#Override
public void onCreate(Bundle savedInstanceState) {
......
viewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));
.......
}
Placed it in method getPOISFromDB()
......
#Override
public void onResponse(String response) {
Log.d(TAG, "Response: " + response);
try {
JSONObject jObj = new JSONObject(response);
JSONArray jsonArray = jObj.getJSONArray("pois");
PointOfInterestLab.get(AppController.getInstance()).clearPointOfInterests();
for(int i=0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
int id = jsonObject.getInt("poi_id");
String name = jsonObject.getString("name");
String summary = jsonObject.getString("summary");
double latitude = jsonObject.getDouble("latitude");
double longitude = jsonObject.getDouble("longitude");
Location location = new Location("dummyProvider");
location.setLatitude(latitude);
location.setLongitude(longitude);
PointOfInterest pointOfInterest = new PointOfInterest(id, name, summary
, location);
PointOfInterestLab.get(AppController.getInstance()).addPointOfInterest(pointOfInterest);
}
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
}
viewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));
}
.....

make a marker clickable only once in android google map v2

I am displaying a set of marker in my Google Map and I want to make the makerss clickable only once. If I click on the same marker again I should get a message like "already clicked" or something like that. How can i do it?
public void getData() {
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(DATA_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
parseData(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(jsonArrayRequest);
}
private void parseData(JSONArray array) {
for (int i = 0; i < array.length(); i++) {
JSONObject json = null;
try {
json = array.getJSONObject(i);
place1 = json.getString("place");
Lat1 = json.getString("latitude");
Long1 = json.getString("longitude");
sensor = json.getString("sensor1");
bin_capacity = json.getString("capacity");
if (Integer.parseInt(sensor) >= 0 && Integer.parseInt(sensor) <= 60) {
LatLng latLng = new LatLng(Double.parseDouble(Lat1), Double.parseDouble(Long1));
arrayLatlong.add(latLng);
for (int j = 0; j < arrayLatlong.size(); j++) {
arrayPlace.add(place1);
bin.add(bin_capacity);
myMarker= map.addMarker(new MarkerOptions().position(latLng).title(bin_capacity));
arrayMarker.add(myMarker);
map.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
for (int k = 0; k < arrayMarker.size(); k++) {
if (marker.equals(arrayMarker.get(k))) {
counter++;
capacity.setText("Capacity = "+counter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Use boolean to maintain the state :
boolean isMarkerClicked = false;
And update in onclicklistener
map.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
if(!isMarkerClicked){
isMarkerClicked = true;
//put your rest of code that will work on marker click
}else{
//show here toast message
}
}
});
try with this
on marker click listener this code
googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
//Toast.makeText(MapActivity.this, marker.getTitle(), Toast.LENGTH_SHORT).show();// display toast
return false;
}
});
// marker title and messages clickable use this code
googleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
if (marker.getTitle().equals("Your Location")) {
} else {
Toast.makeText(MapActivity.this, map.get("" + marker_list.indexOf(marker.getTitle())).get("stylistUserId"), Toast.LENGTH_SHORT).show();
}
}
});
In this case what you can do is create a Temporary ArrayList() or HashMap().
Inside your onMarkerClick() method check if our temp list contains the marker, if yes show the toast and if not add the marker to temp list.
Replace folowing code:
map.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
for (int k = 0; k < arrayMarker.size(); k++) {
if (marker.equals(arrayMarker.get(k))) {
counter++;
capacity.setText("Capacity = " + counter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
with this:
map.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
if (arrayMarker.contains(marker)) {
//show here toast message
} else {
arrayMarker.add(marker);
//put your rest of code that will work on marker click
}
}
}

How to add multiple markers on a google map parsed from json array?

I have written a program in which on button click i am getting the nearby atms from json . This is the link
https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=19.052696,72.8713694&radius=1000&types=atm&sensor=true&key=AIzaSyA8szrI9Ue4EwyUwTgz7Nk0c39qMal0pN4
I want to plot the atms on google map but the problem is only the last atm is being displayed on the map
Code : Method to get the atm names , latitude , longitude and vicinity
public void showAtm(){
String getAtmUrl =
"https://maps.googleapis.com/maps/api/place/nearbysearch/json?
location="+lat+","+lng+"&radius=1000&types=atm&sensor=true
&key=AIzaSyA8szrI9Ue4EwyUwTgz7Nk0c39qMal0pN4";
try{
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder().url(getAtmUrl).build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
Map_Activity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getBaseContext(), "Request to atm
locations failed", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onResponse(Call call, Response response) throws
IOException {
Log.i("response ", "onResponse(): " + response);
String result = response.body().string();
Log.i("result",result);
try{
JSONObject jsonObject = new JSONObject(result);
String resultData = jsonObject.getString("results");
JSONArray urlDetails = new JSONArray(resultData);
for (int i = 0 ; i < urlDetails.length(); i++){
JSONObject json = urlDetails.getJSONObject(i);
geometry = json.getString(GOEMETRY);
vicinity = json.getString(VICINITY);
JSONObject jsonGeometry = new JSONObject(geometry);
String geoLocation =
jsonGeometry.getString(LOCATION);
JSONObject jsonLatLng = new JSONObject(geoLocation);
atmLat = jsonLatLng.getDouble(LATITUDE);
atmLong = jsonLatLng.getDouble(LONGITUDE);
atmName = json.getString(ATM_NAME);
Log.i("JsonArrayAtm", "" + atmName);
Log.i("JsonArrayGeometry",geometry);
Log.i("LatLong",""+atmLat+" , "+atmLong);
Log.i("Vicinity", vicinity);
runOnUiThread(new Runnable() {
#Override
public void run() {
moveAtmMap(atmLat ,atmLong );
}
});
}
}catch (Exception e){
e.printStackTrace();
}
}
});
}catch (Exception e){
e.printStackTrace();
}
}
///////////////////////////// atm locations map ///////////////////
private void moveAtmMap(Double amtLatitude,Double atmLongitude){
fragment.getMap().clear();
CameraPosition position = CameraPosition.builder()
.target(new LatLng(amtLatitude, atmLongitude))
.zoom(16f)
.bearing(0.0f)
.tilt(0.0f)
.build();
String msg = amtLatitude+ ", " + atmLongitude;
LatLng latLng = new LatLng(amtLatitude, atmLongitude);
fragment.getMap().addMarker(new MarkerOptions()
.position(latLng));
fragment.getMap().setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter()
{
#Override
public View getInfoWindow(Marker marker) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
View v = getLayoutInflater().inflate(R.layout.atm_custom_window,
null);
TextView atmHeader = (TextView) v.findViewById(R.id.atmName);
TextView atmLocation = (TextView)
v.findViewById(R.id.atmLocation);
atmHeader.setText(atmName);
atmLocation.setText(vicinity);
return v;
}
});
fragment.getMap().setMapType(GoogleMap.MAP_TYPE_NORMAL);
fragment.getMap().setTrafficEnabled(true);
fragment.getMap().setMyLocationEnabled(true);
fragment.getMap().animateCamera(CameraUpdateFactory
.newCameraPosition(position), null);
}
How do i achieve the above , can anyone suggest me ?
Thanks
You have written the method as,
private void moveAtmMap(Double amtLatitude,Double atmLongitude){
fragment.getMap().clear();
...
}
so every time this method will be called, it will clear all previous markers and you will end up having only the last marker.
Edit
for (int i = 0 ; i < urlDetails.length(); i++){
JSONObject json = urlDetails.getJSONObject(i);
String geometry = json.getString(GOEMETRY);
String vicinity = json.getString(VICINITY);
JSONObject jsonGeometry = new JSONObject(geometry);
String geoLocation = jsonGeometry.getString(LOCATION);
JSONObject jsonLatLng = new JSONObject(geoLocation);
double atmLat = jsonLatLng.getDouble(LATITUDE);
double atmLong = jsonLatLng.getDouble(LONGITUDE);
String atmName = json.getString(ATM_NAME);
runOnUiThread(new Runnable() {
#Override
public void run() {
moveAtmMap(atmLat, atmLong, atmName, vicinity, geometry);
}
});
}
and change method like,
private void moveAtmMap(Double amtLatitude,Double atmLongitude, String name, String vicinity, String geometry)
If you want to clear markers from previous web service hit, then do it before you start adding markers for new service hit, like before the for loop.
Remove this line from the method moveAtmMap:
fragment.getMap().clear();
For the first time, write it before for loop in onResponse.
Try this simple code,
for(int i=0;i<jsonArray.length();i++){
MarkerOptions markerOptions;
markerOptions = new MarkerOptions().position(new LatLng(lattitude,
longitude)
).title("Title").snippet("This is snippet");
markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_icon));
marker = googleMap.addMarker(markerOptions);
}
Just replace lattitude,longitude with your values.
If you want to have instance of each marker,then you can put each "marker" object into hashmap with key as marker id. Let me know your feedback.
Note: remove this line - fragment.getMap().clear(); because it will clear map everytime when compiler comes into loop and it will take only last object. this is what happenng right now.

Show custom infoWindow for multiple markers using Android Mapbox SDK

I am trying to visualize multiple markers on map. Its showing perfectly and onMarkerTap its showing information retrieved from database as JSON. What I want to do is showing the information in a custom layout or bottom sheet. When user tap on marker a bottom sheet will appear with the information related to that marker. I am using the following code for the showing of multiple markers. here on MapViewListener section onTapMarker I have set the marker.getTitle() to show the marker name in the Toast for test. But it is showing the same marker name for all markers. But in the infoWindow built in that show on map showing accurate data. How can I solve this?
FloatingActionButton layerButton = (FloatingActionButton)findViewById(R.id.layer);
layerButton.setOnClickListener(new View.OnClickListener() {
public void getData() {
String url = Config.DATA_URL;
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
});
requestQueue.add(stringRequest);
}
public void showJSON(String response){
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray(Config.JSON_ARRAY);
for (int i=0;i<jsonArray.length();i++){
JSONObject singleMarker = jsonArray.getJSONObject(i);
String poi_name = singleMarker.getString(Config.POI_NAME);
String poi_latitude = singleMarker.getString(Config.POI_LATITUDE);
String poi_longitude = singleMarker.getString(Config.POI_LONGITUDE);
Double dbl_latitude = Double.parseDouble(poi_latitude);
Double dbl_longitude = Double.parseDouble(poi_longitude);
final Marker marker = new Marker(poi_name, poi_thananame, new LatLng(dbl_latitude, dbl_longitude));
marker.setMarker(getResources().getDrawable(R.mipmap.poi_shopping));
mapView.addMarker(marker);
mapView.setMapViewListener(new MapViewListener() {
#Override
public void onShowMarker(MapView pMapView, Marker pMarker) {
}
#Override
public void onHideMarker(MapView pMapView, Marker pMarker) {
}
#Override
public void onTapMarker(MapView pMapView, Marker pMarker) {
Toast.makeText(getApplicationContext(), " Name: "+marker.getTitle()+, Toast.LENGTH_LONG).show();
}
#Override
public void onLongPressMarker(MapView pMapView, Marker pMarker) {
}
#Override
public void onTapMap(MapView pMapView, ILatLng pPosition) {
}
#Override
public void onLongPressMap(MapView pMapView, ILatLng pPosition) {
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
//
// mapView.setCenter(new LatLng(dbl_latitude, dbl_longitude));
// mapView.setZoom(18);
}
//////END OF GET DATA///////
#Override
public void onClick(View v) {
clearLayerFAB.setVisibility(View.VISIBLE);
getData();
}
});
happy to help you out with this one. I assume you are using the 3.2.0 version of the Mapbox Android SDK. If so, I see two problems with your code posted above.
1) You are setting up your listener within the for loop so every time you add a marker your just reseting the listener.
2) Both 3.2.0 and the newer 4.0.0 have a setOnMarkerClickListener method you can call and within it you can add your toast. So it will looks something like this:
for (int i=0;i<jsonArray.length();i++){
// Add your markers here
}
// Setup your listener here
mapView.setOnMarkerClickListener(new MapboxMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(#NonNull Marker marker) {
Toast.makeText(getApplicationContext(), " Name: "+marker.getTitle()+, Toast.LENGTH_LONG).show();
return false;
}
});
Hopefully this helps!

Categories

Resources