I have an application that will update the google map marker with the latest latitude and longitude from the real time Firebase. I have a problem with removing a markers on google maps, The problem is when there is a new marker appear on the map, the previous marker couldn't be removed. I tried to use GoogleMap.clear() but it seem like not working. Does anyone know what caused this issue ?Thanks !
My code
public class PoliceMapActivity extends FragmentActivity implements OnMapReadyCallback {
//initialize all variables
DatabaseReference reff;
GoogleMap map;
String RecordId;
Marker marker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_police_map);
SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.police_map);
supportMapFragment.getMapAsync(PoliceMapActivity.this);
//get record Id
RecordId = getIntent().getStringExtra("recordId");
reff = FirebaseDatabase.getInstance().getReference().child("Records");
Thread thread = new Thread() {
#Override
public void run() {
try {
while (isInterrupted()) {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
// update onmapready()
if (supportMapFragment != null) {
supportMapFragment.getMapAsync(PoliceMapActivity.this);
if (marker != null) {
map.clear();
}
}
}
});
}
} catch (InterruptedException e) {
}
}
};
thread.start();
}
#Override
public void onMapReady(GoogleMap googleMap) {
map.clear();
final DatabaseReference finalreff = reff.child(RecordId);
finalreff.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
Double lat = (Double) snapshot.child("latitude").getValue();
Double lon = (Double) snapshot.child("longitude").getValue();
String name = snapshot.child("Fullname").getValue().toString();
LatLng latLng = new LatLng(lat, lon);
googleMap.addMarker(new MarkerOptions().position(latLng).title(getIntent().getStringExtra(name)));
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 18));
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
you may have invoked map.clear() on a different object and not on the googleMap instance you are showing in the code.
try to invoke googleMap.clear() in the method onDataChange
Related
I've got a problem with reading data from google firebase. It seems like the method onDataChange is not called no matter if I change data in the database or not and I don't know why. What makes me curious is that I am able to write data into the database. I would be very thankful if someone could help me. Here is my code:
public class MainActivity extends AppCompatActivity implements LocationListener, View.OnClickListener {
MapView mapView;
MyLocationNewOverlay myLocationOverlay;
private static final String TAG = "MainActivity";
String content = "a";
String author = "b";
Double latitude = 53.2;
Double longitude = 11.5;
private ItemizedIconOverlay<OverlayItem> messagesOverlay;
private List<OverlayItem> items = new ArrayList<>();
private long totalNumberChilds;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//set up the mapView and show the MyLocationOverlay
mapView = findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mapView.setMultiTouchControls(true);
mapView.getController().setZoom(5);
messagesOverlay = new ItemizedIconOverlay<OverlayItem>(items, getResources().getDrawable(R.drawable.briefumschlag), null, this);
myLocationOverlay = new MyLocationNewOverlay(new GpsMyLocationProvider(getApplicationContext()), mapView);
myLocationOverlay.enableMyLocation();
mapView.getOverlays().add(messagesOverlay);
mapView.getOverlays().add(myLocationOverlay);
GeoPoint point = this.myLocationOverlay.getMyLocation();
if(point==null){
return;
} else {
mapView.getController().animateTo(point);
}
//initialize the Overlay for the Messages
//messagesOverlay.addItem(new OverlayItem(author, "", new GeoPoint(latitude, longitude)));
//declare the database variables in onCreate
//NOTE: Unless you are signed in, this will not be useable.
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("message");
// Read from the database
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
messagesOverlay.removeAllItems();
Toast.makeText(MainActivity.this, "yesss", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDataChange: Successsfully called!");
for (DataSnapshot ds : dataSnapshot.getChildren()) {
//Message message = new Message();
//String author1 = ds.child("messageAuthor").getValue(String.class);
//String content1 = ds.child("messageContent").getValue(String.class);
//Double latitude1 = ds.child("messageLatitude").getValue(Double.class);
//Double longitude1 = ds.child("messageLongitude").getValue(Double.class);
//messagesOverlay.addItem(new OverlayItem("by" + author1, "", new GeoPoint(latitude1, longitude1)));
}
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
}
});
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.testButton) {
addMessage();
}
}
public void addMessage() {
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("message");
String id = myRef.push().getKey();
Message message = new Message(author, content, latitude, longitude);
myRef.child(id).setValue(message);
Toast.makeText(this, "Message added", Toast.LENGTH_LONG).show();
}
#Override
public void onLocationChanged(Location location) {
GeoPoint point = new GeoPoint(location);
if(point==null){
return;
} else {
mapView.getController().animateTo(point);
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
I just found the error, I removed the lines
if(point==null){
return;
} else {
mapView.getController().animateTo(point);
}
and now the onDataChange method is called. Thank you so much for your help!
I have a Firebase Realtime database, where I store Google Maps Marker data. It looks like this: Firebase Database
My application has the option to add your own marker to the database, my problem is that my application only reads the info from Studio 1 and T1, not from the random key added by .push(). when i add a marker via the app. Any ideas on how to get it to read the marker info that is under the random key? My code looks as follows:
public class MapsActivity extends FragmentActivity implements
OnMapReadyCallback, GoogleMap.OnMarkerClickListener {
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference mProfileRef = firebaseDatabase.getReference("Studios");
ChildEventListener mChildEventListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
Button addAStudio = (Button) findViewById(R.id.addAStudio);
addAStudio.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MapsActivity.this, Rent.class);
startActivity(intent);
}
});
}
#Override
public void onMapReady(GoogleMap googleMap){
googleMap.setOnMarkerClickListener(this);
LatLng Copenhagen = new LatLng(55.67, 12.56);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(Copenhagen, 18));
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//get marker info from Firebase Database and add to map
addMarkersToMap(googleMap);
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
googleMap.setMyLocationEnabled(true);
}
#Override
public void onStop(){
if(mChildEventListener != null)
mProfileRef.removeEventListener(mChildEventListener);
super.onStop();
}
private void addMarkersToMap(final GoogleMap map){
mChildEventListener = mProfileRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
FirebaseMarker marker = dataSnapshot.getValue(FirebaseMarker.class);
String StudioName = marker.getStudioName();
String StudioAdress = marker.getStudioAddress();
String StudioDescription = marker.getStudioDescription();
double latitude = marker.getLatitude();
double longitude = marker.getLongitude();
LatLng location = new LatLng(latitude, longitude);
map.addMarker(new MarkerOptions()
.position(location)
.title(StudioName)
.snippet(StudioAdress)
.snippet(StudioDescription))
.showInfoWindow();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public boolean onMarkerClick(Marker marker) {
return false;
}
And
public class FirebaseMarker {
public String studioName;
public String studioDescription;
public String studioAddress;
public double latitude;
public double longitude;
//required empty constructor
public FirebaseMarker() {
}
public FirebaseMarker(String studioName, String studioDescription, String studioAdress, double latitude, double longitude) {
this.studioName = studioName;
this.studioDescription = studioDescription;
this.studioAddress = studioAdress;
this.latitude = latitude;
this.longitude = longitude;
}
public String getStudioName() {
return studioName;
}
public void setStudioName(String studioName) {
this.studioName = studioName;
}
public String getStudioDescription() {
return studioDescription;
}
public void setStudioDescription(String studioDescription) {
this.studioDescription = studioDescription;
}
public String getStudioAddress() {
return studioAddress;
}
public void setStudioAddress(String studioAddress) {
this.studioAddress = studioAddress;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
}
and finally where add a new marker to the database:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rent);
saveStudio = findViewById(R.id.saveStudio);
studioNameTextField = findViewById(R.id.studioNameTextField);
studioInfoTextField = findViewById(R.id.studioInfoTextField);
studioAdressTextField = findViewById(R.id.studioAdressTextField);
mDatabase = FirebaseDatabase.getInstance();
mDataBaseRef = mDatabase.getReference("Studios");
saveStudio = findViewById(R.id.saveStudio);
saveStudio.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
Map<String, FirebaseMarker> newStudioAdd = new HashMap<>();
newStudioAdd.put(studioNameTextField.getText().toString(),
new FirebaseMarker(
studioNameTextField.getText().toString(),
studioInfoTextField.getText().toString(),
studioAdressTextField.getText().toString(),
53.669115, 12.560311
)
);
mDataBaseRef.push().setValue(newStudioAdd);
Intent intent = new Intent(Rent.this, MapsActivity.class);
startActivity(intent);
}
});
}
as of now the latitude and longitude are hardcoded, as i want it to read the markers before i continue.
This is happening because Studio 1 and T1 have different paths than the T2. As I see in your database schema, your T2 as an extra child (-LH-3 ... GbsF) which is generated by the push() method. In order to display all those objects correctly, you need to have the same paths for all objects. So you can achieve this, either by adding Studio 1 and T1 in the same way, using the push() method or by adding the T2 without using the push() method.
FirebaseMarker firebaseMarker = new FirebaseMarker(
studioNameTextField.getText().toString(),
studioInfoTextField.getText().toString(),
studioAdressTextField.getText().toString(),
53.669115, 12.560311);
mDataBaseRef.push().setValue(firebaseMarker);
Assuming that the Studios node is a direct child of your Firebase database, here is how you can add the markers on the map:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference studiosRef = rootRef.child("Studios");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
FirebaseMarker marker = dataSnapshot.getValue(FirebaseMarker.class);
String StudioName = marker.getStudioName();
String StudioAdress = marker.getStudioAddress();
String StudioDescription = marker.getStudioDescription();
double latitude = marker.getLatitude();
double longitude = marker.getLongitude();
LatLng location = new LatLng(latitude, longitude);
map.addMarker(new MarkerOptions()
.position(location)
.title(StudioName)
.snippet(StudioAdress)
.snippet(StudioDescription))
.showInfoWindow();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
studiosRef.addListenerForSingleValueEvent(valueEventListener);
I have a map activity in my app, and I'm trying to make that when I open the map activity, it will zoom in automatically to my location but instead it zooms in every some seconds.
This is my code:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private static final String FIREBASE_URL="https://****.firebaseio.com/";
private Firebase firebaseRef;
private LocationManager locationManager;
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps2);
Firebase.setAndroidContext(this);
firebaseRef = new Firebase(FIREBASE_URL);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
setUpMapIfNeeded();
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
final String title = marker.getTitle().toString();
firebaseRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot user : dataSnapshot.child("users").getChildren()) {
String event_title = user.child("event/event_title").getValue().toString();
if (title.equals(event_title)) {
String event_date = user.child("event/event_date").getValue().toString();
String event_content = user.child("event/event_content").getValue().toString();
String age_limit = user.child("event/age_limit").getValue().toString();
String event_hour = user.child("event/event_hour").getValue().toString();
String location_left = user.child("location_left").getValue().toString();
String location_right = user.child("location_right").getValue().toString();
final SharedPreferences sp = getSharedPreferences("key", 0);
final SharedPreferences.Editor sedt = sp.edit();
sedt.putString("event_title", event_title);
sedt.putString("event_date", event_date);
sedt.putString("event_content", event_content);
sedt.putString("age_limit", age_limit);
sedt.putString("event_hour", event_hour);
sedt.putString("location_left", location_left);
sedt.putString("location_right", location_right);
sedt.commit();
}
}
Intent intent = new Intent(MapsActivity.this, EventInfo.class);
startActivity(intent);
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
return true;
}
});
}
private void setUpMapIfNeeded() {
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
} else {
Toast.makeText(MapsActivity.this, "You have to accept!", Toast.LENGTH_LONG).show();
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
}
}
if (mMap != null) {
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location arg0) {
CameraUpdate center= CameraUpdateFactory.newLatLng(new LatLng(arg0.getLatitude(), arg0.getLongitude()));
CameraUpdate zoom=CameraUpdateFactory.zoomTo(12);
mMap.moveCamera(center);
mMap.animateCamera(zoom);
}
});
}
}
}
#Override
public void onMapReady(final GoogleMap googleMap) {
mMap=googleMap;
firebaseRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child : dataSnapshot.child("users").getChildren()) {
String rightLocation = child.child("location_right").getValue().toString();
String leftLocation = child.child("location_left").getValue().toString();
double location_left = Double.parseDouble(leftLocation);
double location_right = Double.parseDouble(rightLocation);
String event_title = child.child("event/event_title").getValue().toString();
LatLng cod = new LatLng(location_left, location_right);
googleMap.addMarker(new MarkerOptions().position(cod).title(event_title));
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
}
}
I can guess that it is a problem in my setUpMapIfNeeded() method, but I can't find the problem.
What am I doing wrong?
The problem is due to below code
CameraUpdate center= CameraUpdateFactory.newLatLng(new LatLng(arg0.getLatitude(), arg0.getLongitude()));
CameraUpdate zoom=CameraUpdateFactory.zoomTo(12);
mMap.moveCamera(center);
mMap.animateCamera(zoom);
As onMyLocationChange listener is getting called when their is any change in location.
So if you required to change to center of map to latest location then you have do write code to check the actual displacement between previous location.
If actually displacement was happened then only you can change the center and zoom of the map.
I am using map to get current location and now I want to send my current location to another activity which has form to input all the data.
I am confused about which variables and methods I should use to send the location data.
ChooseFromMapActivity
This is the activity where I am getting my current location. And now on Click of useLocation layout I want to send this location to the edit text of another activity i.e GoSendActivity.
public class ChooseFromMapActivity extends AppCompatActivity implements
LocationListener, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private LocationRequest mLocationRequest;
GoogleMap mGoogleMap;
private GoogleApiClient mGoogleApiClient;
boolean mUpdatesRequested = false;
private LatLng center;
private LinearLayout markerLayout;
private Geocoder geocoder;
private List<Address> addresses;
private TextView Address;
double latitude;
double longitude;
private GPSTracker gps;
private LatLng curentpoint;
private LinearLayout useLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choose_from_map);
Address = (TextView) findViewById(R.id.textShowAddress);
markerLayout = (LinearLayout) findViewById(R.id.locationMarker);
useLocation = (LinearLayout)findViewById(R.id.LinearUseLoc);
int status = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getBaseContext());
if (status != ConnectionResult.SUCCESS) { // Google Play Services are
// not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this,
requestCode);
dialog.show();
} else { // Google Play Services are available
// Getting reference to the SupportMapFragment
// Create a new global location parameters object
mLocationRequest = LocationRequest.create();
/*
* Set the update interval
*/
mLocationRequest.setInterval(GData.UPDATE_INTERVAL_IN_MILLISECONDS);
// Use high accuracy
mLocationRequest
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Set the interval ceiling to one minute
mLocationRequest
.setFastestInterval(GData.FAST_INTERVAL_CEILING_IN_MILLISECONDS);
// Note that location updates are off until the user turns them on
mUpdatesRequested = false;
/*
* Create a new location client, using the enclosing class to handle
* callbacks.
*/
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
mGoogleApiClient.connect();
}
useLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
private void stupMap() {
try {
mGoogleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// Enabling MyLocation in Google Map
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
mGoogleMap.getUiSettings().setCompassEnabled(true);
mGoogleMap.getUiSettings().setRotateGesturesEnabled(true);
mGoogleMap.getUiSettings().setZoomGesturesEnabled(true);
gps = new GPSTracker(this);
gps.canGetLocation();
latitude = gps.getLatitude();
longitude = gps.getLongitude();
curentpoint = new LatLng(latitude, longitude);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(curentpoint).zoom(19f).tilt(70).build();
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
// Clears all the existing markers
mGoogleMap.clear();
mGoogleMap.setOnCameraChangeListener(new OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition arg0) {
// TODO Auto-generated method stub
center = mGoogleMap.getCameraPosition().target;
mGoogleMap.clear();
markerLayout.setVisibility(View.VISIBLE);
try {
new GetLocationAsync(center.latitude, center.longitude)
.execute();
} catch (Exception e) {
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
}
#Override
public void onConnected(Bundle arg0) {
// TODO Auto-generated method stub
stupMap();
}
private class GetLocationAsync extends AsyncTask<String, Void, String> {
// boolean duplicateResponse;
double x, y;
StringBuilder str;
public GetLocationAsync(double latitude, double longitude) {
// TODO Auto-generated constructor stub
x = latitude;
y = longitude;
}
#Override
protected String doInBackground(String... params) {
try {
geocoder = new Geocoder(ChooseFromMapActivity.this, Locale.ENGLISH);
addresses = geocoder.getFromLocation(x, y, 1);
str = new StringBuilder();
if (Geocoder.isPresent()) {
if ((addresses != null) && (addresses.size() > 0)) {
Address returnAddress = addresses.get(0);
String localityString = returnAddress.getLocality();
String city = returnAddress.getCountryName();
String region_code = returnAddress.getCountryCode();
String zipcode = returnAddress.getPostalCode();
str.append(localityString + "");
str.append(city + "" + region_code + "");
str.append(zipcode + "");
}
} else {
}
} catch (IOException e) {
Log.e("tag", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(String result) {
try {
Address.setText(addresses.get(0).getAddressLine(0)
+ addresses.get(0).getAddressLine(1) + " ");
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
#Override
public void onConnectionSuspended(int arg0) {
// TODO Auto-generated method stub
}
}
GoSendActivity
This is my GoSendActivity which has edit text view. I want to get the current location on edttxt_from text view.
public class GoSend extends AppCompatActivity {
LatLng latLng;
private GoogleMap mMap;
MarkerOptions markerOptions;
LinearLayout ll;
Toolbar toolbar;
EditText editTextLocation;
EditText edtxt_from;
EditText edtxt_to;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gosendlayout);
setUI();
if (Build.VERSION.SDK_INT >= 21) {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
public void setUI() {
ll = (LinearLayout) findViewById(R.id.LinearLayoutGoSend);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("GO-SEND");
try {
if (mMap == null) {
mMap = ((MapFragment) getFragmentManager().
findFragmentById(R.id.map)).getMap();
}
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
mMap.setMyLocationEnabled(true);
} catch (Exception e) {
e.printStackTrace();
}
edtxt_from=(EditText)findViewById(R.id.editText_from);
edtxt_to=(EditText)findViewById(R.id.editText_to);
edtxt_from.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(),PickLocationActivity.class);
startActivity(i);
}
});
edtxt_to.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(),PickLocationActivity.class);
startActivity(i);
}
});
}
}
Location class
public class Location {
private int id;
private String mFrom_loc;
private String mTo_loc;
private String mFromloc_details;
private String mToloc_details;
private String mItems_details;
public Location(int id,String mFrom_loc,String mFromloc_details,String mTo_loc,String mToloc_details,String mItems_details)
{
this.id=id;
this.mFrom_loc=mFrom_loc;
this.mFromloc_details=mFromloc_details;
this.mTo_loc=mTo_loc;
this.mToloc_details=mToloc_details;
this.mItems_details=mItems_details;
}
public Location(String mFrom_loc){
this.mFrom_loc=mFrom_loc;
}
public Location(){}
public int getId(int id){return id;}
public String getmFrom_loc(String mFrom_loc){return mFrom_loc;}
public String getmTo_loc(String mTo_loc){return mTo_loc;}
public String getmFromloc_details(String mFromloc_details){return mFromloc_details;}
public String getmToloc_details(String mToloc_details){return mToloc_details;}
public String getmItems_details(String mItems_details){return mItems_details;}
public void setId(){this.id=id;}
public void setmFrom_loc(){this.mFrom_loc=mFrom_loc;}
public void setmTo_loc(){this.mTo_loc=mTo_loc;}
public void setmFromloc_details(){this.mFromloc_details=mFromloc_details;}
public void setmToloc_details(){this.mToloc_details=mToloc_details;}
public void setmItems_details(){this.mItems_details=mItems_details;}
}
How can I achieve this?? Please help..
try this :
useLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ChooseFromMapActivity.this , GoSendActivity.class);
intent.putExtra("Latitude", latitude);
intent.putExtra("Longitude", longitude);
startActivity(intent);
}
});
And inside onCreate of GoSendActivity,get latitude and longitude like this :
Bundle extras = getIntent().getExtras();
if (extras != null) {
double latitude = extras.getDouble("Latitude");
double longitude = extras.getDouble("Longitude");
}
Now you can set latitude and longitude to your edittext edittext.setText(String.valueOf(latitude));
Apart from passing the data to the next activity using intents, you can also use shared preferences, TinyDB lib achieves great results for caching data. Yoou will need to sync this in your gradle file :
compile 'com.mukesh:tinydb:1.0.1'
then in your onCreate in each activity you will be using the same, initialize the tinyDB by passing application context
TinyDB tinyDB = new TinyDB(getApplicationContext());
With that you can store and retrieve any data within the app using a key-value pair,example to store your coordinates, just call :
tinyDB.putDouble("latitude",latitude);
tinyDB.putDouble("longitude",longitude);
And you can retrieve the data this way:
double latitude = tinyDB.getDouble("latitude");
double longitude = tinyDB.getDouble("longitude");
This class supports all data formats, from Strings,Double,Float and even objects such as ararayLists. Would highly recommend you to try it out.
Make this class as serialisable and put it into intent using bundle.putSerializable("myclaa",location).
Class Location implements Seraializable{
}
I am trying to make an app that will show my current location and will track me from there with a line.I have been using Google maps Api v2 for android so i was trying to work with polylines to help me show my tracks but its not showing.
Can anyone help me with that..Thankyou.
Total code is provided.
public class MainActivity extends FragmentActivity implements ConnectionCallbacks,
OnConnectionFailedListener, LocationListener,
OnMyLocationButtonClickListener, OnClickListener, android.location.LocationListener {
private GoogleMap mMap;
private LocationClient mLocationClient;
private TextView mMessageView;
private boolean setIt;
// These settings are the same as the settings for the map. They will in fact give you updates
// at the maximal rates currently possible.
private static final LocationRequest REQUEST = LocationRequest.create()
.setInterval(5000) // 5 seconds
.setFastestInterval(16) // 16ms = 60fps
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_location_demo);
mMessageView = (TextView) findViewById(R.id.message_text);
Button b1=(Button)findViewById(R.id.start);
Button b2=(Button)findViewById(R.id.stop);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
setUpLocationClientIfNeeded();
mLocationClient.connect();
}
#Override
public void onPause() {
super.onPause();
if (mLocationClient != null) {
mLocationClient.disconnect();
}
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationButtonClickListener(this);
}
}
}
private void setUpLocationClientIfNeeded() {
if (mLocationClient == null) {
mLocationClient = new LocationClient(
getApplicationContext(),
this, // ConnectionCallbacks
this); // OnConnectionFailedListener
}
}
/**
* Button to get current Location. This demonstrates how to get the current Location as required
* without needing to register a LocationListener.
*/
public void showMyLocation(View view) {
if (mLocationClient != null && mLocationClient.isConnected()) {
String msg = "Location = " + mLocationClient.getLastLocation();
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
LocationManager locationmanager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationmanager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
if (v.getId() == R.id.start) {
setIt = true;
};
if (v.getId() == R.id.stop) {
mMap.clear();
};
}
PolylineOptions rectOptions = new PolylineOptions().width(3).color(
Color.RED);
#Override
public void onLocationChanged(Location location) {
mMessageView.setText("Location = " + location);
rectOptions.add(new LatLng(location.getLatitude(), location.getLongitude()));
if (setIt == true){
mMap.addPolyline(rectOptions);
}
}
#Override
public void onConnected(Bundle connectionHint) {
mLocationClient.requestLocationUpdates(
REQUEST,
this); // LocationListener
}
/**
* Callback called when disconnected from GCore. Implementation of {#link ConnectionCallbacks}.
*/
#Override
public void onDisconnected() {
// Do nothing
}
/**
* Implementation of {#link OnConnectionFailedListener}.
*/
#Override
public void onConnectionFailed(ConnectionResult result) {
// Do nothing
}
#Override
public boolean onMyLocationButtonClick() {
{
setIt = true;
};
Toast.makeText(this, "MyLocation button clicked", Toast.LENGTH_SHORT).show();
// Return false so that we don't consume the event and the default behavior still occurs
// (the camera animates to the user's current position).
return false;
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
This is very easy to in Google Map API V2 . If you would like to do this then you can follow this reference link:
Go this stackoverflow link
This man already give useful solution. I have done the same way as this site told.
For your facility I have written the main things:
1.create a list of LatLng points such as:
List<LatLng> routePoints;
2.Add the route points to the list (could/should be done in a loop):
routePoints.add(mapPoint);
3.Create a Polyline and feed it the list of LatLng points as such:
Polyline route = map.addPolyline(new PolylineOptions()
.width(_strokeWidth)
.color(_pathColor)
.geodesic(true)
.zIndex(z));
route.setPoints(routePoints);
Try this and give feedback!!!