Displaying markers in a certain radius in Android - android

I am making an app that uses maps api. I have a bunch of markers on the server. What I want to do is display only the markers in the certain radius of user's current location (for example, show all markers in a 10 kilometer radius from my current location).
MapFragment:
if (myLocation != null) {
latitude = myLocation.getLatitude();
longitude = myLocation.getLongitude();
}
MarkerOptions markerOptions = new MarkerOptions().position(
new LatLng(latitude, longitude)).icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_me));
mMap.addMarker(markerOptions);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(latitude, longitude)).zoom(12).build();
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
#Override
public void onMapLongClick(final LatLng arg0) {
RequestQueue queue = Volley.newRequestQueue(getActivity());
String url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + String.valueOf(arg0.latitude) + "," + String.valueOf(arg0.longitude) + "&key=myKey";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jObj = new JSONObject(response).getJSONArray("results").getJSONObject(0).getJSONArray("address_components");
Intent intent = new Intent(getActivity(), SetRestaurantActivity.class);
for (int i = 0; i < jObj.length(); i++) {
String componentName = new JSONObject(jObj.getString(i)).getJSONArray("types").getString(0);
if (componentName.equals("postal_code") || componentName.equals("locality") || componentName.equals("street_number") || componentName.equals("route")
|| componentName.equals("neighborhood") || componentName.equals("sublocality") || componentName.equals("administrative_area_level_2")
|| componentName.equals("administrative_area_level_1") || componentName.equals("country")) {
intent.putExtra(componentName, new JSONObject(jObj.getString(i)).getString("short_name"));
}
}
intent.putExtra("latitude", arg0.latitude);
intent.putExtra("longitude", arg0.longitude);
startActivity(intent);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
int x = 1;
}
});
queue.add(stringRequest);
}
});
MyRestaurantsFragment:
public class RestaurantsFragment extends Fragment {
private static final String TAG = RestaurantsFragment.class.getSimpleName();
// Restaurants json url
private ProgressDialog pDialog;
private List<Restaurant> restaurantList = new ArrayList<>();
private ListView listView;
private CustomListAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_restaurants, container, false);
listView = (ListView) view.findViewById(R.id.restaurants_list);
adapter = new CustomListAdapter(getActivity(), restaurantList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading...");
pDialog.show();
SQLiteHandler db = new SQLiteHandler(getActivity().getApplicationContext());
HashMap<String, String> user = db.getUserDetails();
final String userId = user.get("uid");
StringRequest restaurantReq = new StringRequest(Request.Method.POST,
AppConfig.URL_GET_RESTAURANT, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
JSONArray restaurants = jObj.getJSONArray("restaurant");
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < restaurants.length(); i++) {
try {
JSONObject obj = restaurants.getJSONObject(i);
Restaurant restaurant = new Restaurant();
restaurant.setUserName(obj.getString("name"));
if (obj.getString("image") != null && !obj.getString("image").isEmpty()) {
restaurant.setThumbnailUrl(obj.getString("image"));
}
restaurant.setLat(obj.getString("latitude"));
restaurant.setLon(obj.getString("longitude"));
restaurant.setDate(obj.getString("restaurant_name"));
restaurant.setTime(obj.getString("restaurant_description"));
// adding restaurant to restaurant array
restaurantList.add(restaurant);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
} else {
// Error. Get the error message
String errorMsg = jObj.getString("error_msg");
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
},

Use SphericalUtils method computeDistanceBetween() from google-maps-utils to calculate distance from your position to every restaurant and filter out its collection by calculated distance
...
restaurant.setDate(obj.getString("restaurant_name"));
restaurant.setTime(obj.getString("restaurant_description"));
restaurant.setLat(obj.getString("latitude"));
restaurant.setLon(obj.getString("longitude"));
// adding restaurant to restaurant array
if (SphericalUtil.computeDistanceBetween(new LatLng(restaurant.getLat(), restaurant.getLon()), userLatLng)<10)
restaurantList.add(restaurant);
}

Related

while sending array from android to server 1st element sets at server side 0 value but in android it sets correct value what is the solution

server data
android data
I am passing arraylist of srid of all element and post to server using volley request.enter image description here
here is the code
public class AttendenceShowStdList extends AppCompatActivity {
ActivityAttendenceShowStdListBinding AttendenceShowStdList;
ArrayList<AttStdListModel> userlist = new ArrayList<>();
ArrayList<AllStdListsrIdAdmIdModel> list= new ArrayList<>();
ArrayList<AllStdListModel> stdlist = new ArrayList<>();
AttStdListAdapter adapter;
private DatePickerDialog datePickerDialog;
private String date,clid,sectionId,yrId,instId,usid,usType,attdate;
SharedPreferences sharedPreferences_teach;//staff shareprefferece for profile fetch
private static final String SHARED_PREF_NAME_TEACH="myprefteach";
private static final String Key_USID_TEACH = "techusid";
private static final String Key_INSTID_TEACH = "techinstid";
private static final String Key_USTYPE_TEACH = "techustype";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AttendenceShowStdList= ActivityAttendenceShowStdListBinding.inflate(getLayoutInflater());
setContentView(AttendenceShowStdList.getRoot());
sharedPreferences_teach =getSharedPreferences(SHARED_PREF_NAME_TEACH, Context.MODE_PRIVATE);
instId=sharedPreferences_teach.getString(Key_INSTID_TEACH,null);
usid=sharedPreferences_teach.getString(Key_USID_TEACH,null);
usType=sharedPreferences_teach.getString(Key_USTYPE_TEACH,null);
//getting data from TakeAttendenceAdapter cardview
clid=getIntent().getExtras().getString("ClassId");
sectionId=getIntent().getExtras().getString("sectionId");
Log.d("cliddd",clid);
yrId=getIntent().getExtras().getString("YearId");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
date = sdf.format(new Date());
Log.d("dttt",date);
userlist = (ArrayList<AttStdListModel>) getModel(false);
adapter = new AttStdListAdapter(this,userlist);
AttendenceShowStdList.rvstdlist.setAdapter(adapter);
AttendenceShowStdList.rvstdlist.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));
// recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
// recyclerView.setHasFixedSize(true);
getData();
//toolbar
setSupportActionBar(AttendenceShowStdList.toolbar);
Objects.requireNonNull(getSupportActionBar()).setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
AttendenceShowStdList.submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
submitAttendence();
// Intent intent = new Intent(AttendenceShowStdList.this,SubmitAttendenceActivity.class);
// startActivity(intent);
}
});
}
private List<AttStdListModel> getModel(boolean isSelect){
List<AttStdListModel> list = new ArrayList<>();
for(int i = 0; i < list.size(); i++){
AttStdListModel model = new AttStdListModel();
model.setSelected(isSelect);
// model.setStud_name(String.valueOf(list.get(i)));
model.setAdmi_id(String.valueOf(list.get(i)));
list.add(model);
}
return list;
}
private void getData() {
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
String url1="https://comzent.in/wonderschoolerp/apis/teacher/get_studteachers_att.php";
StringRequest request = new StringRequest(Request.Method.POST, url1, new com.android.volley.Response.Listener<String>() {
#SuppressLint("NotifyDataSetChanged")
#Override
public void onResponse(String response) {
// Toast.makeText(getContext(), "Data added to API", Toast.LENGTH_SHORT).show();
try {
JSONObject respObj = new JSONObject(response);
JSONArray jsonArray5=respObj.getJSONArray("studatt_details");
Log.d("std details",jsonArray5.toString());
for(int i=0;i<jsonArray5.length();i++){
JSONObject jsonObject=jsonArray5.getJSONObject(i);
String sr_id=jsonObject.optString("sr_id");
String admi_id=jsonObject.optString("admi_id");
String stud_name=jsonObject.optString("stud_name");
String stud_phone=jsonObject.optString("stud_phone");
String stud_email=jsonObject.optString("stud_email");
String attd_status=jsonObject.optString("attd_status");
String attd_reason=jsonObject.optString("attd_reason");
userlist.add(new AttStdListModel(sr_id,admi_id,stud_name,stud_phone,stud_email,
attd_status,attd_reason));
Log.d("s", String.valueOf(userlist));
list.add(new AllStdListsrIdAdmIdModel(sr_id,admi_id,stud_name,stud_phone,stud_email,
attd_status,attd_reason));
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter=new AttStdListAdapter(getApplicationContext(),userlist);
AttendenceShowStdList.rvstdlist.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Fail to get response = " + error, Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("get_studattd","1");
params.put("us_id",usid);
params.put("inst_id",instId);
params.put("class_id",clid);
params.put("sec_id",sectionId);
params.put("ay_id",yrId);
params.put("stud_attend_date",date);
return params;
}
};
queue.add(request);
}
//submit attendence
private void submitAttendence() {
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
String url1="https://comzent.in/wonderschoolerp/apis/teacher/take_studteacher_att.php";
StringRequest request = new StringRequest(Request.Method.POST, url1, new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Toast.makeText(getContext(), "Data added to API", Toast.LENGTH_SHORT).show();
try {
JSONObject respObj = new JSONObject(response);
String msg=respObj.getString("message");
Toast.makeText(AttendenceShowStdList.this, msg, Toast.LENGTH_LONG).show();
Log.d("response msg",msg);
if(msg.equals("Attendance Generated Successfully..!")){
finish();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Fail to get response = " + error, Toast.LENGTH_LONG).show();
Log.d("error msg", String.valueOf(error));
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
ArrayList<String> allstdsrid = new ArrayList<String>();
for(int i=0; i < list.size(); i++) {
allstdsrid.add(String.valueOf(list.get(i).getSr_id()));
}
params.put("sr_id", String.valueOf(allstdsrid));
Log.d("params", String.valueOf(params));
Log.d("allstudentsrid", String.valueOf(allstdsrid));
ArrayList<String> allstdadmid = new ArrayList<String>();
for(int i=0; i < list.size(); i++) {
allstdadmid.add(list.get(i).getAdmi_id());
params.put("admission_id", String.valueOf(allstdadmid));
}
Log.d("allstudentsadmid", String.valueOf(allstdadmid));
///selected student list
ArrayList<String> attstd = new ArrayList<String>();
for (int i = 0; i < AttStdListAdapter.userlist.size(); i++) {
if (AttStdListAdapter.userlist.get(i).getSelected()) {
attstd.add(AttStdListAdapter.userlist.get(i).getAdmi_id());
}
}
params.put("student_attend_submit","1");
params.put("class_id",clid);
params.put("sec_id",sectionId);
params.put("ay_id",yrId);
params.put("att_status", String.valueOf(attstd));
Log.d("params", String.valueOf(params));
params.put("stud_attend_date",date);
params.put("inst_id",instId);
params.put("us_id",usid);
params.put("us_type",usType);
return params;
}
};
queue.add(request);
}
//toolbar back to home
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if(item.getItemId()==android.R.id.home){
finish();
}
return super.onOptionsItemSelected(item);
}
}
After submitting attendance, values of array of srid and admid retrive at server correctly ,problem is that only first record's srid and admid sets to '0' value.There is no problem when same Api is fetch on postman.

How to make a multicolored overview polyline?

I have added an overview polyline in my map but now I want it look multicolored on different latitudes and longitudes.
If you can please help me find how to get through this problem I will be grateful
public void User(final Context context,final GoogleMap gMap) {
Log.d("seee",makeURL());
final MarkerOptions markerOptions=new MarkerOptions();
final StringRequest stringRequest = new StringRequest(Request.Method.POST, makeURL(), new Response.Listener<String>() {
List<LatLng> startLatLng=null;
#Override
public void onResponse(String response) {
JSONObject json=null;
try {
json = new JSONObject(response);
JSONArray routeArray = json.getJSONArray("routes");
for(int i=0;i<routeArray.length();i++) {
JSONObject routes = routeArray.getJSONObject(i);
JSONArray rAQI=routeArray.getJSONObject(i).getJSONArray("legs").getJSONObject(0).getJSONArray("steps");
startLatLng=getLatitudeLongitudes(rAQI);
JSONObject overviewPolylines = routes
.getJSONObject("overview_polyline");
String encodedString = overviewPolylines.getString("points");
List<LatLng> list = PolyUtil.decode(encodedString);
if(i!=0) {
PolylineOptions options = new PolylineOptions().width(17).color(ContextCompat.getColor(context,R.color.colorGreyline)).geodesic(true);
for (int z = 0; z < list.size(); z++) {
LatLng point = list.get(z);
options.add(point);
}
gMap.addPolyline(options);
options.clickable(true);
}
else {
PolylineOptions options = new PolylineOptions().width(20).color(ContextCompat.getColor(context,R.color.colorBlueline)).geodesic(true);
for (int z = 0; z < list.size(); z++) {
LatLng point = list.get(z);
options.add(point);
}
gMap.addPolyline(options);
options.clickable(true);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Toast.makeText(context, ""+startLatLng.size(), Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "" + error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
return params;
}
};
RequestQueue queue = Volley.newRequestQueue(context);
queue.add(stringRequest);
}
I want to get something like this

BasicNetwork.performRequest: Unexpected response code 400,marker doesnt show up

problem : after click on search the marker doesn't show up again and give me error response code 400 for ( link )
logcat error
E/Response:: [{"lat":"-7.552991","lng":"110.798546","id":"13","nama":"SMK 4 NEGERI SURAKARTA"}]
E/Volley: [4208] BasicNetwork.performRequest: Unexpected response code 400 for http://tugasupload.esy.es/api/maps.php?latitude=SMK 4 NEGERI SURAKARTA
and source code
private void getMarkers() {
System.out.println("abc");
dialog.setMessage("Mengambil Data");
dialog.setCancelable(false);
dialog.show();
JsonArrayRequest reqData = new JsonArrayRequest(Request.Method.GET,
"http://tugasupload.esy.es/api/maps.php?latitude=" + ambilcari, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject data = response.getJSONObject(i);
title = data.getString("nama");
id = data.getInt("id");
latLng = new LatLng(Double.parseDouble(data.getString(LAT)), Double.parseDouble(data.getString(LNG)));
lokasi = data.getString("nama");
// Menambah data marker untuk di tampilkan ke google map
addMarker(latLng, title, lokasi, id);
} catch (JSONException e) {
e.printStackTrace();
}
}
dialog.cancel();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
dialog.cancel();
Toast.makeText(getApplication(), "Ada Kesalahan Mohon Periksa Kembali", Toast.LENGTH_LONG).show();
}
});
AppController.getInstance().addToRequestQueue(reqData);
}
#Override
public void onClick(View view) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
assert imm != null;
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
ambilcari = acTextView.getText().toString();
lokasi();
gMap.clear();
}
private void lokasi() {
dialog.setMessage("Loading...");
dialog.show();
String url1 = "http://tugasupload.esy.es/api/lokasi.php?latitude=" + ambilcari;
url1= url1.replaceAll(" ", "%20");
System.out.println(url1);
StringRequest strReq = new StringRequest(Request.Method.GET, url1, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("Response: ", response);
try {
JSONArray jArray = new JSONArray(response);
for (int i = 0; i < jArray.length(); i++) {
JSONObject jsonObject = jArray.getJSONObject(i);
System.out.println(latLng);
lati = Double.parseDouble(jsonObject.getString(LAT));
longi = Double.parseDouble(jsonObject.getString(LNG));
if (ambilcari.equals(" ")) {
center = new LatLng(-7.568737, 110.827062);
cameraPosition = new CameraPosition.Builder().target(center).zoom(10).build();
gMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
getMarkers();
} else {
center = new LatLng(lati, longi);
cameraPosition = new CameraPosition.Builder().target(center).zoom(12).build();
gMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
getMarkers();
}
}
dialog.dismiss();
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse( VolleyError volleyError ) {
try {
String responseBody = new String( volleyError.networkResponse.data, "utf-8" );
JSONObject jsonObject = new JSONObject( responseBody );
} catch ( JSONException e ) {
//Handle a malformed json response
} catch (UnsupportedEncodingException ignored){
}
}
}
);
AppController.getInstance().addToRequestQueue(strReq, tag_json_obj);
}
and i am trying to solve this case by following :
Android Volley - BasicNetwork.performRequest: Unexpected response code 400
and adding url = url.replaceAll(" ", "%20"); before adding this code after search, force close app

Getting marker details when marker is clicked

Hello i have this app that could detect users locations. In 1 activity I am displaying all the markers from mysql server using volley lirary and store in an array.
Now I want to get the data esp. the title of the marker and pass it to a String or a textview when it is clicked do something
here is my code:
handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//Do something after 20 seconds
if(locationsMarker != null){
locationsMarker.remove();
}
StringRequest stringRequest2 = new StringRequest(Request.Method.GET, locs_url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray array= new JSONArray(response);
JSONObject locations;
String from_lat_lng="";
for (int i = 0; i < array.length(); i++) {
locations = new JSONObject(array.get(i).toString());
String locs = locations.getString("current_loc");
Matcher m = Pattern.compile("\\(([^)]+)\\)").matcher(locs);
while(m.find()) {
from_lat_lng = m.group(1) ;
}
String[] gpsVal = from_lat_lng.split(",");
double lat = Double.parseDouble(gpsVal[0]);
double lon = Double.parseDouble(gpsVal[1]);
LatLng location_array = new LatLng(lat,lon);
Toast.makeText(ScanToHelp.this, "haha="+location_array.toString(), Toast.LENGTH_LONG).show();
points.add(location_array); //added
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(location_array);
markerOptions.title("Current Location");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
locationsMarker = mMap.addMarker(markerOptions);
// mMap.moveCamera(CameraUpdateFactory.newLatLng(location_array));
// mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(location_array, 17.2f));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
MySingleton.getInstance(ScanToHelp.this).addToRequestQueue(stringRequest2);
handler.postDelayed(this, 3000);
}
}, 100); //the time is in miliseconds
Thanks,

Refresh map markers on android with button

i am running a web service with some json data which i use to make markers on my map(this gets updated every hour).i want to add button on my android map so that i will refresh the markers data.any idea without changing much of the structure?should i do something on the threads?or restart the activity?
heres is the code
public class MainActivity extends FragmentActivity {
private static final String LOG_TAG = "jsonmap";
private static final String SERVICE_URL = "http://7a27183e.ngrok.com";
public GoogleMap map;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(activity_maps);
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (map == null) {
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.map);
map = mapFragment.getMap();
if (map != null) {
setUpMap();
// new MarkerTask().execute();
}
}
}
private void setUpMap() {
UiSettings settings = map.getUiSettings();
settings.setZoomControlsEnabled(true);
settings.setScrollGesturesEnabled(true);
// Retrieve the city data from the web service
// In a worker thread since it's a network operation.
new Thread(new Runnable() {
public void run() {
try {
retrieveAndAddCities();
} catch (IOException e) {
Log.e(LOG_TAG, "Cannot retrive cities", e);
return;
}
}
}).start();
}
protected void retrieveAndAddCities() throws IOException {
HttpURLConnection conn = null;
final StringBuilder json = new StringBuilder();
try {
// Connect to the web service
URL url = new URL(SERVICE_URL);
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
// Read the JSON data into the StringBuilder
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
json.append(buff, 0, read);
}
} catch (IOException e) {
Log.e(LOG_TAG, "Error connecting to service", e);
throw new IOException("Error connecting to service", e);
} finally {
if (conn != null) {
conn.disconnect();
}
}
// Create markers for the city data.
// Must run this on the UI thread since it's a UI operation.
runOnUiThread(new Runnable() {
public void run() {
try {
createMarkersFromJson(json.toString());
} catch (JSONException e) {
Log.e(LOG_TAG, "Error processing JSON", e);
}
}
});
}
void createMarkersFromJson(String json) throws JSONException {
// De-serialize the JSON string into an array of city objects
JSONArray jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
// Create a marker for each city in the JSON data.
//.title(jsonObj.getString("pollutant")+" "+jsonObj.getString("network"))
// .snippet(Integer.toString(jsonObj.getInt("numeric_val")))
//DATE!!
JSONObject jsonObj = jsonArray.getJSONObject(i);
map.addMarker(new MarkerOptions()
.title(jsonObj.getString("network") + "\n" + jsonObj.getString("date"))
.snippet(jsonObj.getString("pollutant") + "=" + jsonObj.getString("numeric_val"))
.position(new LatLng(
jsonObj.getDouble("x"),
jsonObj.getDouble("y")))
.icon(BitmapDescriptorFactory.defaultMarker(new Random().nextInt(360)))
);
map.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoContents(Marker arg0) {
return null;
}
#Override
public View getInfoWindow(Marker arg0) {
View v = getLayoutInflater().inflate(R.layout.customlayout, null);
TextView tTitle = (TextView) v.findViewById(R.id.title);
TextView tSnippet = (TextView) v.findViewById(R.id.snippet);
tTitle.setText(arg0.getTitle());
tSnippet.setText(arg0.getSnippet());
return v;
}
});
}
}
}
this is the json structure:
https://gist.githubusercontent.com/anonymous/42af315ab003ab01764d/raw/79b6cf5451038bd2e35c376766e9ab44bd385a02/gistfile2.txt
and a screenshot:
http://imgur.com/WZNC9Oz
I have done some modification in your method named createMarkersFromJson() at line map.addMarker(). Now you can use changeMarkerPosition() to change the position of marker.
HashMap<String, Marker> markerHashMap = new HashMap<>();
void changeMarkerPosition(String key, LatLng latLng) {
markerHashMap.get(key).setPosition(latLng);
}
void createMarkersFromJson(String json) throws JSONException {
// De-serialize the JSON string into an array of city objects
JSONArray jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
// Create a marker for each city in the JSON data.
//.title(jsonObj.getString("pollutant")+" "+jsonObj.getString("network"))
// .snippet(Integer.toString(jsonObj.getInt("numeric_val")))
//DATE!!
JSONObject jsonObj = jsonArray.getJSONObject(i);
markerHashMap.put("key"+i,(map.addMarker(new MarkerOptions()
.title(jsonObj.getString("network") + "\n" + jsonObj.getString("date"))
.snippet(jsonObj.getString("pollutant") + "=" + jsonObj.getString("numeric_val"))
.position(new LatLng(
jsonObj.getDouble("x"),
jsonObj.getDouble("y")))
.icon(BitmapDescriptorFactory.defaultMarker(new Random().nextInt(360)))
);)
map.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoContents(Marker arg0) {
return null;
}
#Override
public View getInfoWindow(Marker arg0) {
View v = getLayoutInflater().inflate(R.layout.customlayout, null);
TextView tTitle = (TextView) v.findViewById(R.id.title);
TextView tSnippet = (TextView) v.findViewById(R.id.snippet);
tTitle.setText(arg0.getTitle());
tSnippet.setText(arg0.getSnippet());
return v;
}
});
}

Categories

Resources