I need to show my 'Npc' markers on the map , but the npcList in onMapReady() is empty. How can i put the right way my Npcs from getNPC() npcList in onMapReady() npcList and then display the markers on map
my onMapReady():
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//zoom map camera
// Get LocationManager object
LocationManager locationManager = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);
// Create a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Get the name of the best provider
String provider = (locationManager).getBestProvider(criteria, true);
Location myLocation = (locationManager).getLastKnownLocation(provider);
// myLastLoc = myLocation;
if (myLocation != null) {
//latitude of location
double myLatitude = myLocation.getLatitude();
//longitude og location
double myLongitude = myLocation.getLongitude();
LatLng latLon = new LatLng(myLatitude, myLongitude);
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLon, 17));
}
mGoogleMap.setMyLocationEnabled(true);//koumpi gia location
buildGoogleApiClient(); // mallon mpilia
// locationManager.requestLocationUpdates(provider,1000,1f,com.google.android.gms.location.LocationListener);
npcList = new ArrayList<Npc>();
getNPC();
for(Npc mynpc:npcList) {
if (!npcList.isEmpty()) {
LatLng loc = new LatLng(mynpc.getNpclat(), mynpc.getNpclng());
String name = mynpc.getNpcname();
mGoogleMap.addMarker(new MarkerOptions()
.position(loc)
.title(name));
} else {
Toast.makeText(getActivity().getApplicationContext(), "npcList is empty", Toast.LENGTH_LONG).show();
}
}
}
my getNPC():
private void getNPC() {
StringRequest stringRequest = new StringRequest(Request.Method.POST, Constants.URL_NPC_GET,
new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
Log.i("GAME_TAG", "response caught");
boolean error = obj.getBoolean("error");
if (!error) {
Log.i("GAME_TAG", "response showing return no error");
//converting the string to json array object
JSONArray array = obj.getJSONArray("results");
Log.i("GAME_TAG", "response has " + array.length() + " npcs");
//traversing through all the object
for (int i = 0; i < array.length(); i++) {
//getting npc object from json array
JSONObject npc = array.getJSONObject(i);
//adding the npc to npc list
npcList.add(new Npc(
npc.getInt("npcid"),
npc.getInt("userid"),
npc.getString("npcname"),
npc.getString("npcwelcome"),
(float) npc.getLong("npclat"),
(float) npc.getLong("npclng")
));
Log.i("GAME_TAG", "now arraylist has " + npcList.size() + " npcs");
Npc mynpc = npcList.get(i);
LatLng loc = new LatLng(mynpc.getNpclat(), mynpc.getNpclng());
String name = mynpc.getNpcname();
mGoogleMap.addMarker(new MarkerOptions()
.position(loc)
.title(name));
Log.i("GAME_TAG", "npc name "+ name+" " +loc);
}
Log.i("GAME_TAG", "if this sentence showing and still no marker, lets try adding only one marker");
LatLng loc = new LatLng(npcList.get(0).getNpclat(), npcList.get(0).getNpclng());
String name = npcList.get(0).getNpcname();
mGoogleMap.addMarker(new MarkerOptions()
.position(loc)
.title(name));
Log.i("GAME_TAG", "if this sentence showing and with one marker, something wrong with the loop");
} else {
Log.i("GAME_TAG", "response showing return with error");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity().getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
RequestHandler.getInstance(getActivity()).addToRequestQueue(stringRequest);
}
my Npc class:
package com.example.game1;
public class Npc {
private int npcid;
private int userid;
private String npcname;
private String npcwelcome;
private float npclat;
private float npclng;
public Npc(int npcid,int userid,String npcname,String npcwelcome,float npclat,float npclng){
this.npcid = npcid;
this.userid = userid;
this.npcname = npcname;
this.npcwelcome = npcwelcome;
this.npclat = npclat;
this.npclng = npclng;
}
public int getNpcid() {
return npcid;
}
public int getUserid() {
return userid;
}
public String getNpcname() {
return npcname;
}
public String getNpcwelcome() {
return npcwelcome;
}
public float getNpclat() {
return npclat;
}
public float getNpclng() {
return npclng;
}
}
im retrieving the right values from db as you can see in image bellow
image
please help me im stuck
try this, move your looping for adding marker in response after adding to your arraylist
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//zoom map camera
// Get LocationManager object
LocationManager locationManager = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);
// Create a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Get the name of the best provider
String provider = (locationManager).getBestProvider(criteria, true);
Location myLocation = (locationManager).getLastKnownLocation(provider);
// myLastLoc = myLocation;
if (myLocation != null) {
//latitude of location
double myLatitude = myLocation.getLatitude();
//longitude og location
double myLongitude = myLocation.getLongitude();
LatLng latLon = new LatLng(myLatitude, myLongitude);
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLon, 17));
}
mGoogleMap.setMyLocationEnabled(true);//koumpi gia location
buildGoogleApiClient(); // mallon mpilia
// locationManager.requestLocationUpdates(provider,1000,1f,com.google.android.gms.location.LocationListener);
npcList = new ArrayList<Npc>();
getNPC();
}
your getnpc()
private void getNPC() {
StringRequest stringRequest = new StringRequest(Request.Method.POST, Constants.URL_NPC_GET,
new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
Log.i("GAME_TAG", "response caught");
boolean error = obj.getBoolean("error");
if (!error) {
Log.i("GAME_TAG", "response showing return no error");
//converting the string to json array object
JSONArray array = obj.getJSONArray("results");
Log.i("GAME_TAG", "response has " + array.length() + " npcs");
//traversing through all the object
for (int i = 0; i < array.length(); i++) {
//getting npc object from json array
JSONObject npc = array.getJSONObject(i);
//adding the npc to npc list
npcList.add(new Npc(
npc.getInt("npcid"),
npc.getInt("userid"),
npc.getString("npcname"),
npc.getString("npcwelcome"),
npc.getLong("npclat"),
npc.getLong("npclng")
));
}
Log.i("GAME_TAG", "now arraylist has " + npcList.size() + " npcs");
for (Npc mynpc : npcList) {
LatLng loc = new LatLng(mynpc.getNpclat(), mynpc.getNpclng());
String name = mynpc.getNpcname();
mGoogleMap.addMarker(new MarkerOptions()
.position(loc)
.title(name));
}
Log.i("GAME_TAG", "if this sentence showing and still no marker, lets try adding only one marker");
LatLng loc = new LatLng(npcList.get(0).getNpclat(), npcList.get(0).getNpclng());
String name = npcList.get(0).getNpcname();
mGoogleMap.addMarker(new MarkerOptions()
.position(loc)
.title(name));
Log.i("GAME_TAG", "if this sentence showing and with one marker, something wrong with the loop");
} else {
Log.i("GAME_TAG", "response showing return with error");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity().getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
RequestHandler.getInstance(getActivity()).addToRequestQueue(stringRequest);
}
Hope it helps.
i did a few changes to getNPC() and now it works here is the code:
private void getNPC() {
StringRequest stringRequest = new StringRequest(Request.Method.POST,
Constants.URL_NPC_GET,
new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
Log.i("GAME_TAG", "response caught");
boolean error = obj.getBoolean("error");
if (!error) {
Log.i("GAME_TAG", "response showing return no error");
//converting the string to json array object
JSONArray array = obj.getJSONArray("results");
Log.i("GAME_TAG", "response has " + array.length() + " npcs");
//traversing through all the object
for (int i = 0; i < array.length(); i++) {
//getting npc object from json array
JSONObject npc = array.getJSONObject(i);
//adding the npc to npc list
npcList.add(new Npc(
npc.getInt("npcid"),
npc.getInt("userid"),
npc.getString("npcname"),
npc.getString("npcwelcome"),
(float) npc.getDouble("npclat"),
(float) npc.getDouble("npclng")
));
Log.i("GAME_TAG", "now arraylist has " + npcList.size() +
" npcs");
Npc mynpc = npcList.get(i);
LatLng loc = new LatLng(mynpc.getNpclat(),
mynpc.getNpclng());
String name = mynpc.getNpcname();
mGoogleMap.addMarker(new MarkerOptions()
.position(loc)
.title(name));
Log.i("GAME_TAG", "npc name "+ name+" " +loc);
}
Log.i("GAME_TAG", "if this sentence showing and still no
marker, lets try adding only one marker");
LatLng loc = new LatLng(npcList.get(0).getNpclat(),
npcList.get(0).getNpclng());
String name = npcList.get(0).getNpcname();
mGoogleMap.addMarker(new MarkerOptions()
.position(loc)
.title(name));
Log.i("GAME_TAG", "if this sentence showing and with one marker, something wrong with the loop");
} else {
Log.i("GAME_TAG", "response showing return with error");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity().getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
RequestHandler.getInstance(getActivity()).addToRequestQueue(stringRequest);
}
Related
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,
I have a google maps project where you can type in an address and you will get a marker displaying, the address, the duration (travelling by car), and the distance from the users location to point B. It works great!
My problem though, is that whenever I put a location that is not accessed by a car, the app crashes. I'm not looking for anything major, and I do not need anything else than the driving distance, so for the user to just be told that you can't drive here, is just fine for me.
I'm using JSONParsing to parse the address after an UrlRequest. legs, distance, duration, end_address, end-lat, end-lng, are the values that I'm fetching from this file:
legs: [
{
distance: {
text: "547 km",
value: 547015
},
duration: {
text: "5 h 23 min",
value: 19361
},
end_address: "Montreal, Quebec, Kanada",
end_location: {
lat: 45.5017123,
lng: -73.5672184
},
start_address: "Toronto, Ontario, Kanada",
start_location: {
lat: 43.6533096,
lng: -79.3827656
},
steps: [
{
distance: {
text: "0,3 km",
value: 280
},
duration: {
text: "1 min",
value: 66
},
end_location: {
lat: 43.6557259,
lng: -79.3837337
},
html_instructions: "",
polyline: {
points: "e`miGhmocNs#Rm#N]JmA^KBcAZSFWHe#Nk#Pa#Le#L"
},
start_location: {
lat: 43.6533096,
lng: -79.3827656
},
travel_mode: "DRIVING"
},
So my question is, does anyone have any suggestions as to what kind of conditions I should have for this kind of method to run.
if(!=travel_mode: "DRIVING")
{
Toast.makeText(MapsActivity.this, "You cannot drive there",
Toast.LENGTH:SHORT).show();
}
else
{
execute code;
}
Fetch the travel_mode and have it as a condition somehow? Thank you in advance!
My whole code,
The main class, when you press a button the address will be converted
private void init() {
searchText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
dataTransfer = new Object[2];
url = getDirectionsUrl();
GetDistances getDistances = new GetDistances();
dataTransfer[0] = mMap;
dataTransfer[1] = url;
getDistances.execute(dataTransfer);
return false;
}
});
Building the URL...
private String getDirectionsUrl()
{
//WORKS
//https://maps.googleapis.com/maps/api/directions/json?origin=Toronto&destination=Montreal&key=API_KEY"
StringBuilder googleDirectionsUrl = new StringBuilder("https://maps.googleapis.com/maps/api/directions/json?");
//Possible two textfields with origin being another textfield
googleDirectionsUrl.append("origin="+myLat+","+myLng);
googleDirectionsUrl.append("&destination="+searchText.getText().toString());
googleDirectionsUrl.append("&key="+"API_KEY");
return googleDirectionsUrl.toString();
}
Sending the Url to be parsed...
public class DataParser {
private HashMap<String, String> getDuration(JSONArray googleDirectionsJson) {
HashMap<String, String> googleDirectionsMap = new HashMap<>();
String duration = "";
String distance = "";
String title = "";
Log.d("json response", googleDirectionsJson.toString());
try {
duration = googleDirectionsJson.getJSONObject(0).getJSONObject("duration").getString("text");
distance = googleDirectionsJson.getJSONObject(0).getJSONObject("distance").getString("text");
title = googleDirectionsJson.getJSONObject(0).getString("end_address");
googleDirectionsMap.put("duration", duration);
googleDirectionsMap.put("distance", distance);
googleDirectionsMap.put("end_address", title);
} catch (JSONException e) {
e.printStackTrace();
}
return googleDirectionsMap;
}
public HashMap<String, String> parseDirections(String jsonData) {
JSONArray jsonArray = null;
JSONObject jsonObject;
try {
jsonObject = new JSONObject(jsonData);
jsonArray = jsonObject.getJSONArray("routes").getJSONObject(0).getJSONArray("legs");
} catch (JSONException e) {
e.printStackTrace();
}
return getDuration(jsonArray);
}
private HashMap<String, Double> getLatLng(JSONArray googleLatLngJson) {
HashMap<String, Double> googleLatLngMap = new HashMap<>();
Double latitude = 0.0;
Double longitude = 0.0;
try {
latitude = googleLatLngJson.getJSONObject(0).getJSONObject("end_location").getDouble("lat");
longitude = googleLatLngJson.getJSONObject(0).getJSONObject("end_location").getDouble("lng");
googleLatLngMap.put("lat", latitude);
googleLatLngMap.put("lng", longitude);
Log.d("json response", googleLatLngMap.toString());
} catch (JSONException e) {
e.printStackTrace();
}
return googleLatLngMap;
}
public HashMap<String, Double> parseLatLng(String jsonData) {
JSONArray jsonArray = null;
JSONObject jsonObject;
try {
jsonObject = new JSONObject(jsonData);
jsonArray = jsonObject.getJSONArray("routes").getJSONObject(0).getJSONArray("legs");
} catch (JSONException e) {
e.printStackTrace();
}
return getLatLng(jsonArray);
}
}
Getting the values from the JSONparsed hashmaps and putting them into new hashmaps to add the markers with their values
public class GetDistances extends AsyncTask<Object, String, String>{
GoogleMap mMap;
String url;
String googleDirectionsData;
String duration, distance;
Double latitude, longitude;
LatLng latLng;
String title;
#Override
protected String doInBackground(Object... objects) {
mMap = (GoogleMap)objects[0];
url = (String)objects[1];
HttpHandler httpHandler = new HttpHandler();
try
{
googleDirectionsData = httpHandler.readUrl(url);
}
catch(IOException e)
{
e.printStackTrace();
}
return googleDirectionsData;
}
#Override
protected void onPostExecute(String s)
{
DataParser parser = new DataParser();
HashMap<String, String> directionsList = null;
directionsList = parser.parseDirections(s);
duration = directionsList.get("duration");
distance = directionsList.get("distance");
title = directionsList.get("end_address");
HashMap<String, Double> positionList = null;
positionList = parser.parseLatLng(s);
latitude = positionList.get("lat");
longitude = positionList.get("lng");
latLng = (new LatLng(latitude, longitude));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 13));
MarkerOptions markerOptions = new MarkerOptions()
.position(latLng)
.draggable(true)
.title(title);
markerOptions.snippet("Distance: " + distance + ", " + "Duration: " + duration);
mMap.addMarker(markerOptions);
}
}
"API_KEY" - is my actual key, just trying to keep it private.
SOLVED
I just made a try catch in the onPostExecute method, and it solved the crash.
public class GetDestination extends AsyncTask<Object, String, String>{
GoogleMap mMap;
String url;
String googleDirectionsData;
String duration, distance;
Double latitude, longitude;
LatLng latLng;
String title;
private static Context context;
public GetDestination(Context c){
context = c;
}
public static void showToast(){
Toast.makeText(context, "You can't drive through the oceans!", Toast.LENGTH_LONG).show();
}
#Override
protected String doInBackground(Object... objects) {
mMap = (GoogleMap)objects[0];
url = (String)objects[1];
HttpHandler httpHandler = new HttpHandler();
try
{
googleDirectionsData = httpHandler.readUrl(url);
}
catch(IOException e)
{
e.printStackTrace();
}
return googleDirectionsData;
}
#Override
protected void onPostExecute(String s)
{
try {
DataParser parser = new DataParser();
HashMap<String, String> directionsList = null;
directionsList = parser.parseDirections(s);
duration = directionsList.get("duration");
distance = directionsList.get("distance");
title = directionsList.get("start_address");
HashMap<String, Double> positionList = null;
positionList = parser.parseLatLng(s);
latitude = positionList.get("lat");
longitude = positionList.get("lng");
latLng = (new LatLng(latitude, longitude));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 13));
MarkerOptions markerOptions = new MarkerOptions()
.position(latLng)
.draggable(true)
.title(title);
markerOptions.snippet("Distance: " + distance + ", " + "Duration: " + duration);
mMap.addMarker(markerOptions);
}
catch (Exception e)
{
showToast();
e.printStackTrace();
}
}
}
Be sure to pass in the context in the Mainactivity class,
searchText1.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
dataTransfer = new Object[2];
url = getDirectionsUrl();
GetDestination getDestination = new GetDestination(MapsActivity.this);
dataTransfer[0] = mMap;
dataTransfer[1] = url;
getDestination.execute(dataTransfer);
return false;
}
});
It's great that you have solved the problem yourself. Congrats.
But the better approach will be to put a log in the response and check the difference between the two responses i.e drivable and not drivable.
In this way, you could read the exact response and based on the response you can show different messages to the user.
And of course, a try, catch could be there to handle any kind of exception.
Hope this Helps.
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.
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);
}
How to add TAG to every marker and set the UniqueId on every marker.
Uniqueid's of every marker received from the server
Here is DoInBackgroung Code please help me
for (int i = 0; i < jsonarray.length(); i++) {
// ModelClass s = LoganSquare.parse(jsonarray.getJSONObject(i).toString(), ModelClass.class);
ModelClass modelClass = new Gson().fromJson(jsonarray.getJSONObject(i).toString(), ModelClass.class);
LatLng latLng = new LatLng(Double.parseDouble(modelClass.getLatitude()), Double.parseDouble(modelClass.getLongitude())); // Use your server's methods
latLngList.add(latLng);
Here is code to add marker
private void AddPointer() {
try {
if (marker != null) {
mMap.clear();
Toast.makeText(getApplicationContext(), "Remove", Toast.LENGTH_LONG).show();
}
for (LatLng object : latLngList)
marker = mMap.addMarker(new MarkerOptions().title("User Name").position(object).icon(BitmapDescriptorFactory.fromResource(R.drawable.female4)));
System.out.println(marker.getPosition() + " Marker position.......");
} catch (Exception e) {
Toast.makeText(MainActivity.this, "Error ", Toast.LENGTH_LONG).show();
// mMap.clear();
}
}
OnpostExecute code where i add the Marker that received from the server in this time i have two markers on server with its uniqueId's
protected void onPostExecute(Boolean result) {
// dialog.cancel();
// adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Receicve data from server", Toast.LENGTH_LONG).show();
if (result == false) {
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
AddPointer();
}
Here is Model Class
public class ModelClass {
#SerializedName("longi")
public String longitudeServer;
#SerializedName("lati")
public String latitudeServer;
#SerializedName("uniqueid")
public String uniqueidSserver;
public ModelClass(){
}
public String getLongitude(){
return longitudeServer;
}
public String getLatitude(){
return latitudeServer;
}
public String getUniqueId(){
return uniqueidSserver;
}
}
Try this you can set diffrent marker and give uniqueid or name
// Prepare Model Class like this way
public class LocationDetail
{
public String longitudeServer;
public String latitudeServer;
public String uniqueidSserver;
public String getLongitudeServer() {
return longitudeServer;
}
public void setLongitudeServer(String longitudeServer) {
this.longitudeServer = longitudeServer;
}
public String getLatitudeServer() {
return latitudeServer;
}
public void setLatitudeServer(String latitudeServer) {
this.latitudeServer = latitudeServer;
}
public String getUniqueidSserver() {
return uniqueidSserver;
}
public void setUniqueidSserver(String uniqueidSserver) {
this.uniqueidSserver = uniqueidSserver;
}
}
//Prepare the arraylist like this
try
{
LocationDetail modelclass;
JSONObject jsonObject = null;
ArrayList<LocationDetail> locationDetails = new ArrayList<>();
JSONArray jsonArray = ""; // initilise your server data
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
modelclass = new LocationDetail();
modelclass.setLongitudeServer(Double.parseDouble(jsonObject
.getString("Latitude").toString()));
modelclass.setLatitudeServer(Double.parseDouble(jsonObject
.getString("Longitude").toString()));
modelclass.setUniqueidSserver(jsonObject.getString(
"UniqueId").toString());
list.add(modelclass);
}
}
catch(JSONException e)
{
e.printStackTrace();
}
//Now pass above Arraylist to method
private void showMap(ArrayList<Reach_Us> list) {
double latitude = 0;
double longitude = 0;
try {
// Loading map
initilizeMap();
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.setMyLocationEnabled(true);
// Enable / Disable zooming controls
googleMap.getUiSettings().setZoomControlsEnabled(true);
// Enable / Disable my location button
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
// Enable / Disable Compass icon
googleMap.getUiSettings().setCompassEnabled(true);
// Enable / Disable Rotate gesture
googleMap.getUiSettings().setRotateGesturesEnabled(true);
// Enable / Disable zooming functionality
googleMap.getUiSettings().setZoomGesturesEnabled(true);
// lets place some 10 random markers
for (int i = 0; i <= list.size(); i++) {
latitude = list.get(i).getLatitude();
longitude = list.get(i).getLongitude();
// Adding a marker
MarkerOptions marker = new MarkerOptions()
.position(
new LatLng(list.get(i).getLatitude(), list
.get(i).getLongitude()))
.title(i + ":"
+ list.get(i).getUniqueidSserver().toString());
marker.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW));
googleMap.addMarker(marker);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(list.get(i).getLatitude(), list
.get(i).getLongitude())).zoom(15).build();
googleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
} catch (Exception e) {
e.printStackTrace();
}
}
Pravin i do like this.
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httpGet = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httpGet);
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONArray jsonarray = new JSONArray(data);
latLngList.clear();
try {
LocationDetail modelclass;
JSONObject jsonObject = null;
ArrayList<LocationDetail> locationDetails = new ArrayList<>();
// JSONArray jsonArray = ""; // initilise your server data
for (int i = 0; i < jsonarray.length(); i++) {
jsonObject = jsonarray.getJSONObject(i);
modelclass = new LocationDetail();
modelclass.setLongitudeServer(Double.parseDouble(jsonObject.getString("Latitude").toString()));
modelclass.setLatitudeServer(Double.parseDouble(jsonObject.getString("Longitude").toString()));
modelclass.setUniqueidSserver(jsonObject.getString("UniqueId").toString());
list.add(modelclass);
}
} catch (JSONException e) {
e.printStackTrace();
}
return true;
}
and also
private void showMap(ArrayList<LocationDetail> list) {
double latitude = 0;
double longitude = 0;
try {
// Loading map
initMap();
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.setMyLocationEnabled(true);
// Enable / Disable zooming controls
mMap.getUiSettings().setZoomControlsEnabled(true);
// Enable / Disable my location button
mMap.getUiSettings().setMyLocationButtonEnabled(true);
// Enable / Disable Compass icon
mMap.getUiSettings().setCompassEnabled(true);
// Enable / Disable Rotate gesture
mMap.getUiSettings().setRotateGesturesEnabled(true);
// Enable / Disable zooming functionality
mMap.getUiSettings().setZoomGesturesEnabled(true);
// lets place some 10 random markers
for (int i = 0; i <= list.size(); i++) {
latitude = list.get(i).getLatitudeServer();
longitude = list.get(i).getLongitudeServer();
// Adding a marker
MarkerOptions marker = new MarkerOptions()
.position(
new LatLng(list.get(i).getLatitudeServer(), list
.get(i).getLongitudeServer()))
.title(i + ":"
+ list.get(i).getUniqueidSserver().toString());
marker.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW));
mMap.addMarker(marker);
CameraPosition cameraPosition = new CameraPosition.Builder().target(new LatLng(list.get(i).getLatitudeServer()), list.get(i).getLongitudeServer())).zoom(15).build();
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
} catch (Exception e) {
e.printStackTrace();
}
}
And also in
public class LocationDetail
{
public double longitudeServer;
public double latitudeServer;
public String uniqueidSserver;
public double getLongitudeServer() {
return longitudeServer;
}
public void setLongitudeServer(double longitudeServer) {
this.longitudeServer = longitudeServer;
}
public double getLatitudeServer() {
return latitudeServer;
}
public void setLatitudeServer(double latitudeServer) {
this.latitudeServer = latitudeServer;
}
public String getUniqueidSserver() {
return uniqueidSserver;
}
public void setUniqueidSserver(String uniqueidSserver) {
this.uniqueidSserver = uniqueidSserver;
}
}
But error in this line
CameraPosition cameraPosition = new CameraPosition.Builder().target(new LatLng(list.get(i).getLatitudeServer()), list.get(i).getLongitudeServer())).zoom(15).build(); it shows LatLnd Double Double cannot be applied to Double