maps multiple markers using JSON - android

Hi friends I am working on the google maps where trying to add the marker dynamically using the JSON but I can able to add only two markers first and the last one i am using the for loop please help me out
Json Response
{"status":"Success","locations":[{"id":"2","hotel_name":"Igloo","address":"CMM Court Complex S.O","latitude":"12.9765944","longitude":"77.5992708"},{"id":"3","hotel_name":"The Park","address":"CMM Court Complex S.O","latitude":"12.9765944","longitude":"77.5992708"},{"id":"5","hotel_name":"Pai viceroy","address":"Kadugodi Extention SO","latitude":"12.9967012","longitude":"77.758197"},{"id":"8","hotel_name":"Prominere","address":"EPIP S.O","latitude":"12.9698066","longitude":"77.74996320000002"},{"id":"9","hotel_name":"Jaya","address":"Kadugodi Extention SO","latitude":"12.9967012","longitude":"77.758197"},{"id":"10","hotel_name":"Sitara","address":"Tavarekere S.O","latitude":"12.9342565","longitude":"77.60439930000007"},{"id":"11","hotel_name":"Loyalty","address":"Chandapura S.O","latitude":"12.8016","longitude":"77.7041"},{"id":"12","hotel_name":"Daspalla","address":"Ullalu Upanagar S.O","latitude":"1.370527","longitude":"103.83727999999996"}]}
My Code
private void mapsmethod() {
Display.showLoadingDialog(getActivity(), "Loading Locations");
String mapsurls = Jsonurl.url + "map_locations.php?city=" + Session.getcityname(getActivity());
Display.log(mapsurls);
JsonObjectRequest mapsreq = new JsonObjectRequest(Request.Method.GET, mapsurls, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray mapsarray = response.getJSONArray("locations");
// List<Marker> markers=new ArrayList<Marker>();
for (int i = 0; i < mapsarray.length(); i++) {
JSONObject mapsmarkerobj = mapsarray.getJSONObject(i);
/* MarkerOptions m = new MarkerOptions()
.title(mapsmarkerobj.optString("hotel_name"))
.position(new LatLng(mapsmarkerobj.optDouble("latitude"), mapsmarkerobj.optDouble("longitude")));
bottomap.addMarker(m);*/
/*long latitudemarker=mapsmarkerobj.getLong("latitude");
long longmarker=mapsmarkerobj.getLong("longitude");*/
/*Marker marker = bottomap.addMarker(new MarkerOptions().position(new LatLng(mapsmarkerobj.getLong("latitude"),mapsmarkerobj.getLong("longitude"))).title(mapsmarkerobj.getString("hotel_name")));
markers.add(marker);*/
}
// markers.size();
// Display.log(String.valueOf(markers.size()));
} catch (JSONException e) {
e.printStackTrace();
}
Display.hideLoadingDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Display.log(error.toString());
Display.hideLoadingDialog();
}
});
mapsreq.setRetryPolicy(new DefaultRetryPolicy(500000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(mapsreq);
}

Related

How can make volley if receive empty data from database show a (Toast.makeText ) android

I am developing an application that contains Google Maps I get data of google map from MySQL database by use Volley liberty to make connection between my application and database the code is work fine if database have Longitude and latitude but the problem if I not have data into Field of Longitude and latitude the app is crash.
How I can make volley if receive empty data from database show a (Toast.makeText )or anything other but not crash my app?
private void getMarkers() {
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("Response: ", response.toString());
try {
JSONObject jObj = new JSONObject(response);
String getObject = jObj.getString("location");
JSONArray jsonArray = new JSONArray(getObject);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
//title = jsonObject.getString(TITLE);
latLng = new LatLng(Double.parseDouble(jsonObject.getString(LT)), Double.parseDouble(jsonObject.getString(LG)));
addMarker(latLng, title);
gMap.animateCamera(zoomingLocation(latLng));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error: ", error.getMessage());
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
private CameraUpdate zoomingLocation(LatLng latLng) {
return CameraUpdateFactory.newLatLngZoom(latLng, 7);
}
There are two possibilities of error in your case: data does not exist (getString returns null and parseDouble throws NullPointerException) or not formatted correctly (parseDouble throws NumberFormatException) neither of which you are handling. So modify your loop to look like this and add any handling desired such as a toast in the exception block:
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
//title = jsonObject.getString(TITLE);
// LT or LG strings may not exist (returns null) or not a valid double
// so catch Exception (NullPointerException or NumberFormatException)
try {
latLng = new LatLng(Double.parseDouble(jsonObject.getString(LT)), Double.parseDouble(jsonObject.getString(LG)));
addMarker(latLng, title);
gMap.animateCamera(zoomingLocation(latLng));
} catch (Exception e) {
// do something about error such as display Toast.
}
}
Note that if you display a toast it would be displayed on every error - so it may be better to simply set a flag in the exception block and then after the loop if the flag is true then display the toast ("Some data invalid").

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

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,

No map marker info on click event

I am working on an Android app that shows map markers on an Google Map.
I want to show some info from every marker when the user clicks on it.
Now, the markers are shown, but nothing happens when the user clicks on the marker.
Here is my code:
#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 = mGoogleMap.addMarker(markerOptions);
mGoogleMap.clear();
getMarkers();
//move map camera
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,14));
}
private void getMarkers() {
StringRequest strReq = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("Response: ", response.toString());
try {
JSONObject jObj = new JSONObject(response);
String getObject = jObj.getString("wisata");
JSONArray jsonArray = new JSONArray(getObject);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
title = jsonObject.getString(TITLE);
latLng = new LatLng(Double.parseDouble(jsonObject.getString(LAT)), Double.parseDouble(jsonObject.getString(LNG)));
tipo = jsonObject.getString(TIPO);
Log.d("Response","Tipo ="+tipo);
// Menambah data marker untuk di tampilkan ke google map
addMarker(latLng, title,tipo);
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error: ", error.getMessage());
Toast.makeText(getActivity(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
AppController.getInstance().addToRequestQueue(strReq, tag_json_obj);
}
private void addMarker(LatLng latlng, final String title, final String tipo_reporte) {
markerOptions.position(latlng);
if (tipo_reporte.equals("1")) {
Drawable dr = getResources().getDrawable(R.drawable.reten1);
Bitmap bitmap = ((BitmapDrawable) dr).getBitmap();
Drawable d = new BitmapDrawable(getResources(), Bitmap.createScaledBitmap(bitmap, 100, 100, true));
Bitmap icono = ((BitmapDrawable) d).getBitmap();
markerOptions.icon(BitmapDescriptorFactory.fromBitmap(icono));
markerOptions.snippet(title);
}
mGoogleMap.addMarker(markerOptions);
mGoogleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
Toast.makeText(getContext(), marker.getTitle(), Toast.LENGTH_SHORT).show();
}
});
}
What should I change to get marker info?
Try to replace
setOnInfoWindowClickListener(...)
with
setOnMarkerClickListener(...)
You can use markers with onClickListener.

Displaying markers in a certain radius in 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);
}

Categories

Resources