I am currently working with the google map. I already show the markers and the title and snippet of the marker.
Now my problem is when I click the info window it will be redirected to a new activity and get the data of the marker that was clicked. Here is my code:
public class FindApartment extends Fragment implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener,GoogleMap.OnInfoWindowClickListener {
public static final String ID = "id";
public static final String VERIFICATION = "verification";
private static final String TAG_APARTMENTNAME = "apartmentName";
private static final String TAG_CATEGORY = "Category";
private static final String TAG_PRICE = "price_month";
public static final String LAT = "latt";
public static final String LNG = "longt";
MarkerOptions markerOptions = new MarkerOptions();
CameraPosition cameraPosition;
LatLng center, latLng;
String verification, apartmentname, category, price, id;
GoogleMap mGoogleMap;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
MapView mapView;
String tag_json_obj = "json_obj_req";
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_find_apartment, container, false);
mapView = (MapView) rootView.findViewById(R.id.map1);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
mapView.onResume();
return rootView;
}
#Override
public void onPause() {
super.onPause();
//stop location updates when Activity is no longer active
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions myMarker = new MarkerOptions();
myMarker.position(latLng);
myMarker.title("me");
myMarker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW));
mCurrLocationMarker = mGoogleMap.addMarker(myMarker);
//move map camera
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,17));
getMarkers();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap=googleMap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mGoogleMap.setOnInfoWindowClickListener(this);
if(mGoogleMap!= null){
mGoogleMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker marker) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
View view = getLayoutInflater().inflate(R.layout.info_window, null);
TextView textName = (TextView) view.findViewById(R.id.textName);
TextView textViewPrice = (TextView) view.findViewById(R.id.textViewPrice);
TextView detail = (TextView)view.findViewById(R.id.detail);
LatLng ll = marker.getPosition();
textName.setText(marker.getSnippet());
textViewPrice.setText(marker.getTitle());
detail.setText("click to see full detail");
return view;
}
});
}
I'm using Android Volley and the array is on the Stringrequest. How can I get the data of the marker that was clicked on info window?
private void addMarker(LatLng latLng, String category, final String price, final String id) {
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(price);
markerOptions.snippet(category);
markerOption(verification, markerOptions);
mGoogleMap.addMarker(markerOptions);
}
public void onInfoWindowClick(Marker marker) {
id = marker.getId();
String snippet = marker.getSnippet();
Intent intent = new Intent(getActivity(), InfoWindowActivity.class);
startActivity(intent);
}
private void markerOption(String verification, MarkerOptions markerOptions) {
if(verification.contains("pending")) {
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
}
else {
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
}
}
private void getMarkers() {
String url = Server.URL2 + "markers.php";
final HashMap<String, String> apartmentID = new HashMap<String, String>();
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("apartments");
JSONArray jsonArray = new JSONArray(getObject);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
verification = jsonObject.getString(VERIFICATION);
apartmentname = jsonObject.getString(TAG_APARTMENTNAME);
category = jsonObject.getString(TAG_CATEGORY);
price = jsonObject.getString(TAG_PRICE);
id = jsonObject.getString("userID");
apartmentID.put(ID, id);
latLng = new LatLng(Double.parseDouble(jsonObject.getString(LAT)), Double.parseDouble(jsonObject.getString(LNG)));
// Adds a data marker to show to google map
addMarker(latLng, category, price, id);
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
AppController.getInstance().addToRequestQueue(strReq, tag_json_obj);
}
Intent intent = new Intent(getActivity(), InfoWindowActivity.class);
intent.putExtra("snippet", snippet);
intent.putExtra("id", id)
... //put all your info here
startActivity(intent);
Access that data on next activity for example in onCreate or wherever you need it.
String snippet = getIntent().getStringExtra("snippet");
int id = getIntent().getIntExtra("id");
...//get all your info here
Is it what you were looking for? Question is not completely clear..
I have created an app that shows the list of bar locations by a marker on a map taken from a database on firebase.
each bar has a list of beverages.
what I wish to happen is that when a marker is clicked a new activity will open with the name of the bar selected at the top of the new activity
What i wish to happen is that when the marker is clicked it will open a new activity
//Declaration list of venues
List<Venue> venueList;
//onCreate method
venueList = new ArrayList<>();
mVenues.push().setValue(marker);
//onMapsReady method, gets the venues into the map
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mVenues.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot s : dataSnapshot.getChildren()){
Venue venue = s.getValue(Venue.class);
venueList.add(venue);
for (int i = 0; i < venueList.size(); i++)
{
LatLng latLng = new LatLng(venue.venueLat,venue.venueLong);
if (mMap != null) {
marker = mMap.addMarker(new MarkerOptions()
.position(latLng).title(venue.venueName));
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
//Marker Click Event
//CMarker click event to take user to purchase beverage
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener(){
public boolean onMarkerClick(Marker marker) {
String title = marker.getTitle();
{
for (int i = 0; i < venueList.size();) {
//getting the selected venue
Venue venue = venueList.get(i);
//creating an intent
Intent intent = new Intent(getApplicationContext(), viewbeverageActivity.class);
//putting venue name and id to intent
intent.putExtra(VENUE_ID, venue.getVenueId());
intent.putExtra(VENUE_NAME, venue.getVenueName());
//starting the activity with intent
startActivity(intent);
}
return false;
}
}
});
//Venue Class
package uk.ac.ferry_j2ulster.beerapp;
import com.google.firebase.database.IgnoreExtraProperties;
public class Venue {
private String venueId;
public String venueName;
private String venueType;
public double venueLat;
public double venueLong;
public Venue(){
}
public Venue(String venueId, String venueName, String venueType,double venueLat, double venueLong) {
this.venueId = venueId;
this.venueName = venueName;
this.venueType = venueType;
this.venueLat = venueLat;
this.venueLong = venueLong;
}
public String getVenueId() {
return venueId;
}
public String getVenueName() {
return venueName;
}
public String getVenueType() {
return venueType;
}
public double getVenueLong() { return venueLong;
}
public double getVenueLat() {return venueLat;
}
}
I hope to open a new activity with the bar that was selected as a title at the top
no errors, not sure how to start with this one
The problem is that you are using a loop to go through each Venue, and calling startActivity() for all venues.
Instead, define a HashMap that will map each Marker ID to a Venue ID:
Map<String, String> mMarkerMap = new HashMap<>();
Then, put an entry in the HashMap for each Marker:
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot s : dataSnapshot.getChildren()){
Venue venue = s.getValue(Venue.class);
venueList.add(venue);
for (int i = 0; i < venueList.size(); i++)
{
LatLng latLng = new LatLng(venue.venueLat,venue.venueLong);
if (mMap != null) {
marker = mMap.addMarker(new MarkerOptions()
.position(latLng).title(venue.venueName));
//Added:
mMarkerMap.put(marker.getId(), venue.getVenueId());
}
}
}
}
Then, when the user taps a Marker, get the title and Venue ID from the Marker/HashMap, and send it to the new activity:
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//...........
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
String venueID = mMarkerMap.get(marker.getId());
String venueName = marker.getTitle();
Intent intent = new Intent(MapActivity.this, NewActivity.class);
intent.putExtra(VENUE_NAME, venueName);
intent.putExtra(VENUE_ID, venueID);
startActivity(intent);
return false;
}
});
}
In the new activity, simply get the title and Venue ID Strings passed in:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new);
String venueName = getIntent().getStringExtra(MapActivity.VENUE_NAME);
if (title != null) {
getSupportActionBar().setTitle(title);
}
String venueID = getIntent().getStringExtra(MapActivity.VENUE_ID);
if (venueID != null) {
//use venue ID to get the information about this venue
}
//.......
}
You need to pass venue information also to the activity :
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//...........
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
String title = marker.getTitle();
Venue venue = NULL;
for(int i=0;i<venueList.size();i++)
{
if(venueList.get(i).getTitle().equal(title))
venue = venueList.get(i);
}
Intent intent = new Intent(MapActivity.this, NewActivity.class);
intent.putExtra("title", title);
intent.putExtra("venue",venue.toJSON());
startActivity(intent);
return false;
}
});
}
Make a toJSON() function in your venue class and also fromJSON() which will help you in sending venue data as well.
Hello fellow developer,
I created a map using google map activity in android studio and my class extending AppCompactActivity because i want to use Toolbar. When running onMapReady called twice (i try it using Log.d) but when i am change AppCompactActivity to FragmentActivity it only called once.
Updated Code :
public class Maps extends AppCompatActivity implements OnMapReadyCallback, DatePickerDialog.OnDateSetListener, View.OnCreateContextMenuListener {
Context context;
private GoogleMap mMap;
private LocationManager locationManager;
Location location;
TextView eta, distance, tvfrom, tvto;
EditText txtTruck;
AutoCompleteTextView search;
Bitmap keraniMarker, truck, arrowup, puninar;
BitmapDescriptor bdfKerani = null, bdfTruck = null, bdfArrow = null, bdfPuninar = null;
CardView cardFind;
Button btnfind;
SwitchCompat swTraffic;
/////////////////////
static SwitchCompat swProgress;
TextView tvFilter;
ListView lvOrderTruck;
EditText txtSearch;
ArrayList<Order_Truck_SetGet> complete = new ArrayList<>();
ArrayList<Order_Truck_SetGet> onGoing = new ArrayList<>();
String custCode = "nocust";
static String nopol_to_map = "all";
private Order_Truck_Adapter adapter_order_truck;
////////////////////
ArrayList<String> nop = new ArrayList<>();
ArrayList<LastLocationSetterGetter> lastloc = new ArrayList<>();
ArrayList<LatLng> livelatlng = new ArrayList<>();
ArrayList<startmark> arstart = new ArrayList<>();
ArrayList<String> project = new ArrayList<>();
String lokasi, nama, time, speed, statustitle;
TextView namadet, lokasidet, timedet, txtspeed, txtSPK, txtOMpils, txtOMccms, txtCust, txtDriver, txtRute, tvSiMbl, txtSiMbl;
ImageView call, sms, wa;
String telp = "+6281280688872";
LinearLayout llSpk, llOMpils, llOMccms, llCust, llDriver, llRute, llSiMbl;
private ProgressDialog pDialog;
private Dialog dashDialog, listOrderDialog;
int FLAG_START_DATE = 0;
int FLAG_END_DATE = 1;
int flag = -1;
int flag_menu = 0;
private long mLastClickTime = 0;
static final int LOCATION = 1;
static final int WRITE_EXTERNAL = 2;
static final int CALL_PHONE = 3;
static final int SEND_SMS = 4;
int PERMISSION_ALL = 1;
Marker lastmark = null;
Marker startmark = null;
Marker track_arrow = null;
String pilih = Order_Truck.nopol_to_map;
String projectselect = "all";
LinearLayout llnopol, lldate, lllokasi;
ImageView nopol_arrow, date_arrow, lokasi_arrow;
ListView lvTruck;
ArrayList<Dashboard_Truck_SetGet> dastruck = new ArrayList<>();
private Dashboard_Truck_adapter adapter;
private DisplayMetrics metrics;
private boolean mAscendingOrder[] = {true, true, true};
String classname = this.getClass().getSimpleName();
Thread live = new Thread();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
//set for check permission
String[] PERMISSIONS = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CALL_PHONE, Manifest.permission.SEND_SMS};
if (!hasPermissions(this, PERMISSIONS)) {
ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
}
distance = (TextView) findViewById(R.id.DISTANCE);
eta = (TextView) findViewById(R.id.ETA);
search = (AutoCompleteTextView) findViewById(R.id.search);
cardFind = (CardView) findViewById(R.id.cardFind);
tvfrom = (TextView) findViewById(R.id.txtFrom);
tvto = (TextView) findViewById(R.id.txtTo);
btnfind = (Button) findViewById(R.id.btnFind);
swTraffic = (SwitchCompat) findViewById(R.id.swTraffic);
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
pDialog = new ProgressDialog(this);
pDialog.setMessage("Authenticating...");
pDialog.setCancelable(false);
cekOverlay();
project.add("All Project");
project.add("EXIM");
//set logo for marker
//option 1
BitmapDrawable bitmap_kerani = (BitmapDrawable) getResources().getDrawable(R.drawable.truck);
Bitmap kerani_ico = bitmap_kerani.getBitmap();
keraniMarker = Bitmap.createScaledBitmap(kerani_ico, 100, 100, false);
bdfKerani = BitmapDescriptorFactory.fromBitmap(keraniMarker);
BitmapDrawable bitmap_puninar = (BitmapDrawable) getResources().getDrawable(R.drawable.marker_puninar);
Bitmap puninar_ico = bitmap_puninar.getBitmap();
puninar = Bitmap.createScaledBitmap(puninar_ico, 150, 150, false);
bdfPuninar = BitmapDescriptorFactory.fromBitmap(puninar);
BitmapDrawable bitmap_truck = (BitmapDrawable) getResources().getDrawable(R.drawable.flat_truck);
Bitmap truck_icon = bitmap_truck.getBitmap();
truck = Bitmap.createScaledBitmap(truck_icon, 70, 100, false);
bdfTruck = BitmapDescriptorFactory.fromBitmap(truck);
BitmapDrawable bitmap_arrow = (BitmapDrawable) getResources().getDrawable(R.drawable.green_arrow);
Bitmap arrow_up = bitmap_arrow.getBitmap();
arrowup = Bitmap.createScaledBitmap(arrow_up, 70, 50, false);
bdfArrow = BitmapDescriptorFactory.fromBitmap(arrowup);
tvfrom.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setDate();
flag = FLAG_START_DATE;
}
});
tvto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setDate();
flag = FLAG_END_DATE;
}
});
btnfind.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (tvfrom.getText().length() == 0) {
Toast.makeText(getApplicationContext(), "From date must be filled", Toast.LENGTH_SHORT).show();
} else if (tvto.getText().length() == 0) {
Toast.makeText(getApplicationContext(), "To date must be filled", Toast.LENGTH_SHORT).show();
} else if (pilih.isEmpty()) {
Toast.makeText(getApplicationContext(), "Police number must be choosen", Toast.LENGTH_SHORT).show();
} else {
getcarloc(pilih, projectselect);
}
}
});
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.getUiSettings().setCompassEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setRotateGesturesEnabled(true);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(-3.503399, 112.423781), 4.0f));
swTraffic.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
swTraffic.setText("Traffic ON ");
mMap.setTrafficEnabled(true);
} else {
mMap.setTrafficEnabled(false);
swTraffic.setText("Traffic OFF ");
}
}
});
//GPS LAST POSITION
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
search.setText("");
}
});
Log.d("pilihan", pilih + " ^.^");
getNopol(projectselect);
getcarloc(pilih, projectselect);
mMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() {
#Override
public boolean onMyLocationButtonClick() {
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 15.0f));
return false;
}
});
}
public void getcarloc(final String nopol, final String project) {
if (flag_menu != 2) {
mMap.clear();
livelatlng.clear();
lastloc.clear();
}
Log.d("PILIH2", nopol);
Log.d("LIVESTATUS", String.valueOf(live.getState()));
String url;
showpDialog();
if (flag_menu == 1) {
url = Config.GET_LOCATION_HISTORICAL;
} else {
url = Config.GET_LAST_LOCATION;
}
mMap.addMarker(new MarkerOptions().position(new LatLng(-6.172172, 106.941581)).title("Puninar Jaya Cakung").snippet("Puninar Jaya Cakung").icon(bdfPuninar));
mMap.addMarker(new MarkerOptions().position(new LatLng(-6.128611, 106.941747)).title("Puninar Jaya Nagrak").snippet("Puninar Jaya Nagrak").icon(bdfPuninar));
mMap.addMarker(new MarkerOptions().position(new LatLng(-6.029199, 106.085906)).title("Puninar Jaya Cilegon").snippet("Puninar Jaya Cilegon").icon(bdfPuninar));
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("response", response);
hidepDialog();
try {
JSONObject json = new JSONObject(response);
JSONArray jsonArray = json.getJSONArray("data");
if (String.valueOf(jsonArray).equals("[]")) {
hidepDialog();
if (flag_menu == 1) {
Toast.makeText(getApplicationContext(), "There is No Trip History From " + tvfrom.getText() + " Until " + tvto.getText() + " for " + pilih, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "There is No Data / Location For " + pilih, Toast.LENGTH_SHORT).show();
}
} else {
Log.e("JSONARRAY", String.valueOf(jsonArray));
String vehicle_id = null,
vehicle_number = null;
for (int i = 0; i < jsonArray.length(); i++) {
//Get data last location or live tracking
JSONObject obj = jsonArray.getJSONObject(i);
String position_id = obj.getString("position_id");
if (flag_menu != 1) {
vehicle_id = obj.getString("vehicle_id");
vehicle_number = obj.getString("vehicle_number");
}
String date_time = obj.getString("date_time");
Double longitude = Double.parseDouble(obj.getString("longitude")) / 10000000;
Double latitude = Double.parseDouble(obj.getString("latitude")) / 10000000;
String speed = obj.getString("speed");
String course = obj.getString("course");
String street_name = obj.getString("street_name");
String kecamatan = obj.getString("kecamatan");
String kabupaten = obj.getString("kabupaten");
if (flag_menu != 1) {
lastloc.add(new LastLocationSetterGetter(position_id, vehicle_id, vehicle_number,
date_time, longitude, latitude, speed, course, street_name, kecamatan, kabupaten));
} else {
lastloc.add(new LastLocationSetterGetter(position_id, pilih,
date_time, longitude, latitude, speed, course, street_name, kecamatan, kabupaten));
}
LatLng latLng = new LatLng(latitude, longitude);
if (lastmark != null) {
lastmark.remove();
}
//Log.i("InfoSize", String.valueOf(lastloc.size()));
//create marker for live tracking
if (flag_menu != 0) {
livelatlng.add(latLng);
if (startmark == null) {
//create start marker
startmark = mMap.addMarker(new MarkerOptions().position(latLng).title("Start").snippet(vehicle_number).icon(bdfKerani));
arstart.add(new startmark(street_name, kecamatan, kabupaten, vehicle_number, date_time, speed));
} else {
// create live tracking marker
lastmark = mMap.addMarker(new MarkerOptions().position(latLng).title(pilih).snippet(vehicle_number).icon(bdfTruck));
lastmark.setFlat(true);
lastmark.setRotation(Float.parseFloat(course));
if (lastloc.size() > 2) {
track_arrow = mMap.addMarker(new MarkerOptions()
.position(new LatLng(lastloc.get(lastloc.size() - 2).getLatitude(), lastloc.get(lastloc.size() - 2).getLongitude()))
.title(lastloc.get(lastloc.size() - 2).getPosition_id())
.snippet(lastloc.get(lastloc.size() - 2).getVehicle_number())
.icon(bdfArrow));
track_arrow.setFlat(true);
track_arrow.setRotation(Float.parseFloat(lastloc.get(lastloc.size() - 2).getCourse()));
}
}
if (livelatlng.size() > 1) {
//int ap22 = getResources().getColor(R.color.fbutton_color_wet_asphalt);
int ap23 = ContextCompat.getColor(getApplicationContext(), R.color.fbutton_color_belize_hole);
Polyline line = mMap.addPolyline(new PolylineOptions()
.add(livelatlng.get(livelatlng.size() - 2), livelatlng.get(livelatlng.size() - 1))
.width(10)
.color(ap23));
}
} else {
//create marker for last location
MarkerOptions marker = new MarkerOptions().position(latLng).title(vehicle_number).snippet(vehicle_number).icon(bdfKerani);
mMap.addMarker(marker);
}
}
Log.d("TOTALRECORD", String.valueOf(livelatlng.size()));
if (nopol != "all") {
Log.e("lastloc", String.valueOf(lastloc.size()));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lastloc.get(lastloc.size() - 1).getLatitude(), lastloc.get(lastloc.size() - 1).getLongitude()), 16.0f));
//cardFind.setVisibility(View.VISIBLE);
} else {
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(-4.979218, 107.950524), 5.0f));
}
clickmap();
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("ERRORCATCH", String.valueOf(e));
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hidepDialog();
Log.e("ERROR", String.valueOf(error));
String message = null;
if (error instanceof NetworkError) {
message = "Cannot connect to Internet...Please check your connection!";
} else if (error instanceof ServerError) {
message = "The server could not be found. Please try again after some time!!";
} else if (error instanceof AuthFailureError) {
message = "Cannot connect to Internet...Please check your connection!";
} else if (error instanceof ParseError) {
message = "Parsing error! Please try again after some time!!";
} else if (error instanceof NoConnectionError) {
message = "Cannot connect to Internet...Please check your connection!";
} else if (error instanceof TimeoutError) {
message = "Connection TimeOut! Please check your internet connection.";
}
Log.e("VOLLEYERROR", message);
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("prm_1", nopol);
params.put("project", project);
if (flag_menu == 1) {
params.put("from", tvfrom.getText().toString());
params.put("to", tvto.getText().toString());
}
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
String credentials = "admin_it" + ":" + "admin123";
String auth = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
headers.put("Authorization", auth);
return headers;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(60000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
MySingleton.getInstance(getApplicationContext()).addToRequestQueue(stringRequest);
}
public void getNopol(final String project) {
Log.d("PILIHNOPOL", "NOPOL");
//Get all police Number
StringRequest stringRequest = new StringRequest(Request.Method.POST, Config.GET_NOPOL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
nop.clear();
if (flag_menu == 0) {
nop.add("all");
}
try {
JSONObject json = new JSONObject(response);
JSONArray jsonArray = json.getJSONArray("nopol");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
String plat = obj.getString("vehicle_number").replace(" ", "");
nop.add(plat);
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(Maps.this, android.R.layout.simple_list_item_1, nop);
search.setAdapter(arrayAdapter);
search.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
pilih = parent.getItemAtPosition(position).toString();
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
mMap.clear();
startmark = null;
livelatlng.clear();
arstart.clear();
lastloc.clear();
if (flag_menu != 1) {
getcarloc(pilih, projectselect);
}
//Live Tracking selected
if (flag_menu == 2) {
if (live.getState().equals("TIMED_WAITING")) {
live.interrupt();
try {
live.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
live = new Thread() {
#Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000 * 76);
runOnUiThread(new Runnable() {
#Override
public void run() {
getcarloc(pilih, projectselect);
}
});
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
live.start();
}
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("NORESPONSE", String.valueOf(error));
}
}
) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("project", project);
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
String credentials = "admin_it" + ":" + "admin123";
String auth = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
headers.put("Authorization", auth);
return headers;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(60000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
MySingleton.getInstance(getApplicationContext()).addToRequestQueue(stringRequest);
}
}
This is my library
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.3.0'
compile 'com.android.support:design:25.3.0'
compile 'com.android.support:cardview-v7:25.3.0'
compile 'com.google.android.gms:play-services-maps:10.2.1'
compile 'com.google.android.gms:play-services-location:10.2.1'
compile 'com.akexorcist:googledirectionlibrary:1.0.4'
compile 'cn.pedant.sweetalert:library:1.3'
compile 'com.android.volley:volley:1.0.0'
compile 'com.wdullaer:materialdatetimepicker:2.3.0'
compile 'com.android.support.constraint:constraint-layout:1.0.1'
testCompile 'junit:junit:4.12'
}
Your handling of the Google Map inside your onCreate() method seems slightly different than what I have used and seen. Try using this code instead:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this); // don't pass Maps.this
// rest of your code here
}
My hunch is that somehow you were binding the listener twice, though I can't prove this without trying to duplicate your actual code locally.
//Rahees is class in Parse.com for android from where I want to get the list of nearest location from geopoint g.Rahees class has column name "Locations".
I want to get the list of nearest geopoints from g by comparing it with the geopoints listed in Location column of Rahees class
//******************Rahees Class************************//
#ParseClassName("Rahees")
public class Rahees extends ParseObject {
public Rahees()
{
super();
}
public String getDisplayName() {
return getString("displayName");
}
public void setDisplayName(String value) {
put("displayName", value);
}
public static ParseQuery<Rahees> getQuery() {
return ParseQuery.getQuery(Rahees.class);
}
}
//************Main Activity*******************************//
public class MainActivity extends AppCompatActivity {
ParseGeoPoint g;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ParseUser cuser = ParseUser.getCurrentUser();
Rahees haila = new Rahees();
haila.setDisplayName("Rahim");
}
//button for Logging out of system
public void logout(View view)
{
ParseUser.logOut();
Intent intent = new Intent(MainActivity.this, SignUp_Login.class);
startActivity(intent);
}
//Button for going to Map Masti class, it is this button which triggers to compare the geopoint g with the geopoints in the server
public void go_to_maps(View view)
{
Intent intent = new Intent(MainActivity.this, Map_Masti.class);
startActivity(intent);
}
}
//****************************MapMasti Class*****************************//
public class Map_Masti extends FragmentActivity {
ParseGeoPoint g;
private TextView textView;
private SupportMapFragment mapFragment;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_masti);
textView = (TextView)findViewById(R.id.text);
mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map_fragment);
//Query to get the geopoint g from server
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.getInBackground("ccm3xKMmr4", new GetCallback<ParseUser>() {
public void done(ParseUser object, ParseException e) {
if (e == null) {
g = (ParseGeoPoint) object.get("user_Location");
Log.d("mohit", g + "");
} else {
// something went wrong
Log.d("mohit", e + " ");
}
}
});
//query to compare which geopoints in the object "Rahees" with column "Locations" are near to geopoing "g"
ParseQuery<Rahees> mapQuery1 = Rahees.getQuery();
mapQuery1.whereWithinKilometers("Locations", g, 6000);
mapQuery1.setLimit(3);
mapQuery1.findInBackground(new FindCallback<Rahees>() {
#Override
public void done(List<Rahees> objects, ParseException e) {
// Handle the results
if (e == null) {//****this is where the exception error comes, it doesn't goes inside if statement****
for (int i = 0; i < objects.size(); i++) {
Log.d("mohit", "2" + objects.get(i).get("Locations"));
}
} else {
Log.d("mohit", "" + e);
}
}
});
}
}
Below is the error I am getting , from the else part
01-10 12:27:38.655 4348-4348/? D/error: com.parse.ParseRequest$ParseRequestException: $nearSphere needs a map operator
I am able to retrive value of g from Parse,output of Log for g is :
ParseGeoPoint[40.000000,30.000000]
Please help
You should do second query only after will get result of first one, because g is null until will be initialized by callback.
Update:
public class Map_Masti extends FragmentActivity {
ParseGeoPoint g;
private SupportMapFragment mapFragment;
private TextView textView;
private void getG() {
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.getInBackground("ccm3xKMmr4", new GetCallback<ParseUser>() {
public void done(ParseUser object, ParseException e) {
if (e == null) {
g = (ParseGeoPoint) object.get("user_Location");
Log.d("mohit", g + "");
getLocations();
} else {
// something went wrong
Log.d("mohit", e + " ");
}
}
});
}
private void getLocations() {
ParseQuery<Rahees> mapQuery1 = Rahees.getQuery();
mapQuery1.whereWithinKilometers("Locations", g, 6000);
mapQuery1.setLimit(3);
mapQuery1.findInBackground(new FindCallback<Rahees>() {
#Override
public void done(List<Rahees> objects, ParseException e) {
// Handle the results
if (e == null) {//****this is where the exception error comes, it doesn't goes inside if statement****
for (int i = 0; i < objects.size(); i++) {
Log.d("mohit", "2" + objects.get(i).get("Locations"));
}
} else {
Log.d("mohit", "" + e);
}
}
});
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_masti);
textView = (TextView) findViewById(R.id.text);
mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map_fragment);
getG();
}
}
I am trying to create route from current location to the direction, now i can use fixed latitude and longitude, but how to use my current location.
this is my file:
public class DirectionActivity3 extends FragmentActivity {
TextView textProgress;
Button buttonAnimate, buttonRequest;
double mLatitude=0;
double mLongitude=0;
GoogleMap mMap;
GoogleDirection gd;
Document mDoc;
LatLng start = new LatLng(mLatitude,mLongitude);
LatLng end = new LatLng(3.158847, 101.713837);
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_direction_1);
mMap = ((SupportMapFragment)getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
mMap.setMyLocationEnabled(true);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(start, 15));
gd = new GoogleDirection(this);
gd.setOnDirectionResponseListener(new OnDirectionResponseListener() {
public void onResponse(String status, Document doc, GoogleDirection gd) {
mDoc = doc;
mMap.addPolyline(gd.getPolyline(doc, 3, Color.RED));
buttonAnimate.setVisibility(View.VISIBLE);
}
});
gd.setOnAnimateListener(new OnAnimateListener() {
public void onStart() {
textProgress.setVisibility(View.VISIBLE);
}
public void onProgress(int progress, int total) {
textProgress.setText((int)((float)progress / total * 100) + "% / 100%");
}
public void onFinish() {
buttonAnimate.setVisibility(View.VISIBLE);
textProgress.setVisibility(View.GONE);
}
});
textProgress = (TextView)findViewById(R.id.textProgress);
textProgress.setVisibility(View.GONE);
buttonRequest = (Button)findViewById(R.id.buttonRequest);
buttonRequest.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
v.setVisibility(View.GONE);
gd.setLogging(true);
gd.request(start, end, GoogleDirection.MODE_DRIVING);
}
});
buttonAnimate = (Button)findViewById(R.id.buttonAnimate);
buttonAnimate.setVisibility(View.GONE);
buttonAnimate.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
v.setVisibility(View.GONE);
gd.animateDirection(mMap, gd.getDirection(mDoc), GoogleDirection.SPEED_VERY_SLOW
, true, false, true, true
, new MarkerOptions().icon(BitmapDescriptorFactory.fromResource(R.drawable.car))
, true, false, null);
}
});
}
public void onPause() {
super.onPause();
gd.cancelAnimated();
}
}
And one more question, I want to use Google Place API to get somewhere's latitude and longitude as direction, and use my current location to create route.
This is my direction file:
public class PlaceActivity3 extends Activity {
final String ApiKey = "AIzaSyDQ6mA6vUHD3cMNqDoblES6q3dFHzNLqs4";
double latitude = 3.158847;
double longitude = 101.713837;
int radius = 1000;
String type = PlaceType.FOOD;
String language = "en";
String keyword = "japan restaurant food";
TextView textStatus;
ListView listView;
GooglePlaceSearch gp;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_place_1);
textStatus = (TextView)findViewById(R.id.textStatus);
listView = (ListView)findViewById(R.id.listView);
gp = new GooglePlaceSearch(ApiKey);
gp.setOnPlaceResponseListener(new OnPlaceResponseListener() {
public void onResponse(String status, ArrayList<ContentValues> arr_data,
Document doc) {
textStatus.setText("Status : " + status);
if(status.equals(GooglePlaceSearch.STATUS_OK)) {
ArrayList<String> array = new ArrayList<String>();
final ArrayList<String> array_photo = new ArrayList<String>();
for(int i = 0 ; i < arr_data.size() ; i++) {
array.add("Name : " + arr_data.get(i).getAsString(GooglePlaceSearch.PLACE_NAME) + "\n"
+ "Address : " + arr_data.get(i).getAsString(GooglePlaceSearch.PLACE_ADDRESS) + "\n"
+ "Latitude : " + arr_data.get(i).getAsString(GooglePlaceSearch.PLACE_LATITUDE) + "\n"
+ "Longitude : " + arr_data.get(i).getAsString(GooglePlaceSearch.PLACE_LONGITUDE) + "\n"
+ "Phone Number : " + arr_data.get(i).getAsString(GooglePlaceSearch.PLACE_PHONENUMBER));
array_photo.add(arr_data.get(i).getAsString(GooglePlaceSearch.PLACE_PHOTO));
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(PlaceActivity3.this
, R.layout.listview_text, array);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
Dialog dialog = new Dialog(PlaceActivity3.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dialog_photo);
dialog.setCancelable(true);
final ImageView imgPhoto = (ImageView)dialog.findViewById(R.id.imgPhoto);
dialog.show();
gp.getPhotoBitmapByWidth(array_photo.get(arg2), 600, ""
, new OnBitmapResponseListener() {
public void onResponse(Bitmap bm, String tag) {
imgPhoto.setImageBitmap(bm);
}
});
}
});
}
}
});
gp.getNearby(latitude, longitude, radius, type, language, keyword);
}
}
For the current location, you can use the LocationServices's getLastLocation() function:
which should look something like this:
public class MainActivity extends ActionBarActivity implements
ConnectionCallbacks, OnConnectionFailedListener {
...
#Override
public void onConnected(Bundle connectionHint) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
mLatitudeText.setText(String.valueOf(mLastLocation.getLatitude()));
mLongitudeText.setText(String.valueOf(mLastLocation.getLongitude()));
}
}
}
https://developer.android.com/training/location/retrieve-current.html#last-known
OR, you can use the Google Maps Location Data API:
https://developers.google.com/maps/documentation/android/location
For your destination's lat/lng, you should use the The Google Geocoding API:
https://developers.google.com/maps/documentation/geocoding/#GeocodingResponses