Change position of MyLocation Button in MapsActivity - java

I am trying to change the position of my location button in my Maps Android App from top to bottom. Seems like it is default in top. Please help me changing the position of it. I have taken the code from the google samples github. This is the new version of code which uses getMapAsync instead of getMap.
MapsActivity.java:
public class MapsActivity extends AppCompatActivity implements GoogleMap.OnMyLocationButtonClickListener,
GoogleMap.OnMyLocationClickListener,
OnMapReadyCallback,
ActivityCompat.OnRequestPermissionsResultCallback {
/**
* Request code for location permission request.
*
* #see #onRequestPermissionsResult(int, String[], int[])
*/
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;
/**
* Flag indicating whether a requested permission has been denied after returning in
* {#link #onRequestPermissionsResult(int, String[], int[])}.
*/
private boolean mPermissionDenied = false;
private GoogleMap mMap;
private PlaceAutocompleteFragment placeAutocompleteFragment;
Marker marker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
placeAutocompleteFragment = (PlaceAutocompleteFragment) getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
// placeAutocompleteFragment.setFilter(new AutocompleteFilter.Builder().setCountry("ID").build());
placeAutocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
final LatLng latLngLoc = place.getLatLng();
if (marker != null) {
marker.remove();
}
marker = mMap.addMarker(new MarkerOptions().position(latLngLoc).title(place.getName().toString()));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLngLoc));
mMap.animateCamera(CameraUpdateFactory.zoomTo(12), 2000, null);
}
#Override
public void onError(Status status) {
Toast.makeText(MapsActivity.this, "" + status.toString(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setOnMyLocationButtonClickListener(this);
mMap.setOnMyLocationClickListener(this);
enableMyLocation();
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng point) {
// Creating a marker
MarkerOptions markerOptions = new MarkerOptions();
// Setting the position for the marker
markerOptions.position(point);
// changing the marker title
double lat = point.latitude;
double lng = point.longitude;
Geocoder gc = new Geocoder(MapsActivity.this);
List<Address> list = null;
try {
list = gc.getFromLocation(lat, lng, 1);
} catch (IOException e) {
e.printStackTrace();
}
Address address = list.get(0);
String sublocality = address.getSubLocality();
// Setting the title for the marker.
// This will be displayed on taping the marker
markerOptions.title(sublocality);
// Clears the previously touched position
mMap.clear();
// Animating to the touched position
mMap.animateCamera(CameraUpdateFactory.newLatLng(point));
// Placing a marker on the touched position
mMap.addMarker(markerOptions);
}
});
}
private void enableMyLocation() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Permission to access the location is missing.
PermissionUtils.requestPermission(this, LOCATION_PERMISSION_REQUEST_CODE,
Manifest.permission.ACCESS_FINE_LOCATION, true);
} else if (mMap != null) {
// Access to the location has been granted to the app.
mMap.setMyLocationEnabled(true);
}
}
#Override
public boolean onMyLocationButtonClick() {
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 onMyLocationClick(#NonNull Location location) {
Toast.makeText(this, "Current location:\n" + location, Toast.LENGTH_LONG).show();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
if (requestCode != LOCATION_PERMISSION_REQUEST_CODE) {
return;
}
if (PermissionUtils.isPermissionGranted(permissions, grantResults,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Enable the my location layer if the permission has been granted.
enableMyLocation();
} else {
// Display the missing permission error dialog when the fragments resume.
mPermissionDenied = true;
}
}
#Override
protected void onResumeFragments() {
super.onResumeFragments();
if (mPermissionDenied) {
// Permission was not granted, display error dialog.
showMissingPermissionError();
mPermissionDenied = false;
}
}
/**
* Displays a dialog with error message explaining that the location permission is missing.
*/
private void showMissingPermissionError() {
PermissionUtils.PermissionDeniedDialog
.newInstance(true).show(getSupportFragmentManager(), "dialog");
}
}

Guys, I have resolved it.
Add the following lines in your on create below SupportMapFragent.
View myLocationButton = mapFragment.getView().findViewById(0x2);
if (myLocationButton != null && myLocationButton.getLayoutParams() instanceof RelativeLayout.LayoutParams) {
// location button is inside of RelativeLayout
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) myLocationButton.getLayoutParams();
// Align it to - parent BOTTOM|LEFT
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, 0);
params.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
// Update margins, set to 80dp
final int margin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 80,
getResources().getDisplayMetrics());
params.setMargins(margin, margin, margin, margin);
myLocationButton.setLayoutParams(params);
}

Related

How to pass the current lat long values from one class to another activity in Android?

I am using googleAPIClient to get the current lat long values using Location. I am getting the values of both my current lat and long in a separate class. I need to pass these current lat and long values inside my MapsActivity ( GoogleMap Activity), Since I have already created the object for the another class, from which I need to get the values, I don't know how to pass the values to this activity from the class.
Here's what I have tried. This is the class which I have created to get the current lat long values:
CurrentValues.java:
public class CurrentValues implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
private static final String TAG = CurrentValues.class.getSimpleName();
private Context context;
private GoogleApiClient mGoogleApiClient;
private Location mLocation;
private LocationManager mLocationManager;
private LocationRequest mLocationRequest;
private long UPDATE_INTERVAL = 2 * 1000; /* 10 secs */
private long FASTEST_INTERVAL = 2000; /* 2 sec */
public CurrentValues( Context context){
mGoogleApiClient = new GoogleApiClient.Builder(context)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mLocationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
checkLocation();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
startLocationUpdates();
mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(mLocation == null){
startLocationUpdates();
}
if (mLocation != null) {
// mLatitudeTextView.setText(String.valueOf(mLocation.getLatitude()));
//mLongitudeTextView.setText(String.valueOf(mLocation.getLongitude()));
} else {
Toast.makeText(context, "Location not Detected", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onConnectionSuspended(int i) {
Log.i(TAG, "Connection Suspended");
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.i(TAG, "Connection failed. Error: " + connectionResult.getErrorCode());
}
#Override
public void onLocationChanged(Location location) {
String msg = "Updated Location: " +
Double.toString(location.getLatitude()) + "," +
Double.toString(location.getLongitude());
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
}
private boolean checkLocation() {
if(!isLocationEnabled())
showAlert();
return isLocationEnabled();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
private boolean isLocationEnabled() {
mLocationManager = (LocationManager)context. getSystemService(Context.LOCATION_SERVICE);
return mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
private void showAlert() {
final AlertDialog.Builder dialog = new AlertDialog.Builder(context);
dialog.setTitle("Enable Location")
.setMessage("Your Locations Settings is set to 'Off'.\nPlease Enable Location to " +
"use this app")
.setPositiveButton("Location Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(myIntent);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
}
});
dialog.show();
}
protected void startLocationUpdates() {
// Create the location request
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(UPDATE_INTERVAL)
.setFastestInterval(FASTEST_INTERVAL);
// Request location updates
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
mLocationRequest, (com.google.android.gms.location.LocationListener) context);
Log.d("reque", "--->>>>");
}
}
Now I need to pass the lat long values I got from this class to MapsActivity. Since I had already created object for the currentvalues class here in this activity, I don't know how to pass the value from there to here.
Here's my MapActivity (GoogleMap Activity)
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private CurrentValues currentValues;
private Location location;
#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);
}
/**
* 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 a 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;
// // Add a marker in Sydney and move the camera
// LatLng sydney = new LatLng(-34, 151);
// mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
//
// LatLng chennai = new LatLng(13.06,80);
// mMap.addMarker(new MarkerOptions().position(chennai).title("Marker in Chennai"));
LatLng latLng = new LatLng(location.getLatitude(),location.getLongitude());
googleMap.addMarker(new MarkerOptions().position(latLng));
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 8f));
// creating object for currentValues class
CurrentValues currentValues = new CurrentValues(this);
}
}
I don't know how to proceed after this to pass the lat long values here. How can I proceed?

Google Maps: New markers are not showing after resuming map activity

I am connecting my app to a sensor, everytime the sensor sends data a marker is placed on a map with data inside info window.
When I am starting the activity the first time. mMap has ID: 21319.
In my onLocationChanged()method I add markers to the map with ID 21319. Then if I press the back button and resume the activity. mMap is created again and has now another ID, let's say ID 22431. With my method addMapPoints() I add the old markers to mMap with ID 22431 with mMap.addMarker(markerOptions) and I can see the markers on the screen. But this time when new data is sent and markers are added inside onLocationChanged() no new markers appear on the screen. When I debug I can see that in onLocationChanged() my mMap has the old ID: 21319 and I do not get any errors. So I guess that the new markers are added to the old map but my screen is showing the new map.
Why is this happening? And how can I solve this problem?
UPDATE I think I have found the problem. At the moment mMap == null when new data is sent. What I now wonder is how can I obtain the map inside OnLocationUpdate() or in OnResume()?
Here is my MapsActivity code
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener
{
public GoogleMap mMap;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
private int co_mV;
private int no2_mV;
LocationRequest mLocationRequest;
private boolean initiateApp;
String currentTime;
TcpClient mTcpClient;
ArrayList<Marker> markerArrayList;
static ArrayList<Double> markerLat = new ArrayList<>();
static ArrayList<Double> markerLng = new ArrayList<>();
static ArrayList<String> markerSnippet = new ArrayList<>();
static ArrayList<String> markerTitle = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
// 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);
initiateApp = true;
markerArrayList = new ArrayList<>();
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
markerArrayList.clear();
}
/**
* 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 a 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.setMapType(GoogleMap.MAP_TYPE_HYBRID);
mMap.setMyLocationEnabled(true);
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
}
}
else {
buildGoogleApiClient();
}
if (markerLat != null) {
addMapPoints();
}
}
/* Here we create the infoWindow **/
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onConnected(Bundle bundle) {
getNewLocation();
new ConnectTask().execute("");
}
public void newData(JSONObject d) {
try {
co_mV = d.getInt("co_mV");
no2_mV = d.getInt("no2_mV");
} catch (JSONException e) {
e.printStackTrace();
}
getNewLocation();
}
public void getTime() {
Calendar cal = Calendar.getInstance();
currentTime = new SimpleDateFormat("HH:mm:ss").format(cal.getTime());
}
public void getNewLocation() {
mLocationRequest = new LocationRequest();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
public void addMapPoints() {
markerArrayList = new ArrayList<>();
for (int i = 0; i < markerLat.size(); i++) {
LatLng latLng = new LatLng(markerLat.get(i), markerLng.get(i));
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(markerTitle.get(i));
markerOptions.snippet(markerSnippet.get(i));
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
Marker marker = mMap.addMarker(markerOptions);
markerArrayList.add(marker);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
if (markerArrayList.size()>1) {
if(location.distanceTo(mLastLocation) < 30) {
markerArrayList.get(markerArrayList.size()-1).remove();
markerArrayList.remove(markerArrayList.size()-1);
markerSnippet.remove(markerSnippet.size()-1);
markerTitle.remove(markerTitle.size()-1);
markerLat.remove(markerTitle.size()-1);
markerLng.remove(markerTitle.size()-1);
Toast.makeText(
getApplicationContext(),
"Reading to close to last reading, replaces last reading", Toast.LENGTH_SHORT).show();
}
}
if (markerArrayList.size() == 8) {
markerArrayList.get(0).remove();
markerArrayList.remove(0);
markerSnippet.remove(0);
markerTitle.remove(0);
markerLat.remove(0);
markerLng.remove(0);
}
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
if (co_mV != 0) {
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerLat.add(location.getLatitude());
markerLng.add(location.getLongitude());
markerOptions.title("Time of reading: " + currentTime);
markerTitle.add("Time of reading: " + currentTime);
markerOptions.snippet("co: " + String.valueOf(co_mV) + " mV, " + "no2: " + String.valueOf(no2_mV) + " mV");
markerSnippet.add("co: " + String.valueOf(co_mV) + " mV, " + "no2: " + String.valueOf(no2_mV) + " mV");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);
markerArrayList.add(mCurrLocationMarker);
}
mLastLocation = location;
Log.d("ADebugTag", "Value: " + Double.toString(location.getLatitude()));
Log.d("ADebugTag", "Value: " + Double.toString(location.getLongitude()));
//move map camera
if(initiateApp){
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));
}
boolean contains = mMap.getProjection()
.getVisibleRegion()
.latLngBounds
.contains(latLng);
if(!contains){
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
}
initiateApp = false;
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Asking user if explanation is needed
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted. Do the
// contacts-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
// Permission denied, Disable the functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
// other 'case' lines to check for other permissions this app might request.
// You can add here other case statements according to your requirement.
}
}
public JSONObject getNewJSON(JSONObject json) {
try {
int humidity = json.getInt("humidity_ppm");
int pressure = json.getInt("pressure_Pa");
int noise = json.getInt("noise_dB");
double lat = mLastLocation.getLatitude();
double lng = mLastLocation.getLongitude();
long time = System.currentTimeMillis() / 1000L;
JSONObject c = new JSONObject();
c.put("time",time);
c.put("lat",lat);
c.put("long",lng);
c.put("humidity",humidity);
c.put("pressure",pressure);
c.put("noise_dB",noise);
return c;
} catch (JSONException e) {
e.printStackTrace();
}
I solve this problem by exiting the application in onDestroy method .
I think when fragment is reused marker cannot be placed in map
#Override
public void onDestroy() {
getActivity().finish();
System.exit(0);
super.onDestroy();
}

Google Maps: How to restore markers when resuming map activity

I am making an app that collects data from a sensor. Every time the sensor sends data, a new marker is placed on a map. When I press back and then resume the map activity all the markers are gone. Is there a way to save and restore each unique marker with its unique MarkerOptions (title,snippet,LatLng) when resuming the activity?
Here is my maps activity
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener
{
private GoogleMap mMap;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
private int co_mV;
private int no2_mV;
LocationRequest mLocationRequest;
private boolean initiateApp;
String currentTime;
TcpClient mTcpClient;
ArrayList<Marker> markerArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
// 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);
initiateApp = true;
markerArrayList = new ArrayList<Marker>();
}
/**
* 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 a 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.setMapType(GoogleMap.MAP_TYPE_HYBRID);
mMap.setMyLocationEnabled(true);
if(mGoogleApiClient == null) {
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
}
}
else {
buildGoogleApiClient();
}
}
}
/* Here we create the infoWindow **/
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onConnected(Bundle bundle) {
getNewLocation();
new ConnectTask().execute("");
}
public void newData(JSONObject d) {
try {
co_mV = d.getInt("co_mV");
no2_mV = d.getInt("no2_mV");
} catch (JSONException e) {
e.printStackTrace();
}
getNewLocation();
}
public void getTime() {
Calendar cal = Calendar.getInstance();
currentTime = new SimpleDateFormat("HH:mm:ss").format(cal.getTime());
}
public void getNewLocation() {
mLocationRequest = new LocationRequest();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
if (markerArrayList.size()>1) {
if(location.distanceTo(mLastLocation) < 30) {
markerArrayList.get(markerArrayList.size()-1).remove();
markerArrayList.remove(markerArrayList.size()-1);
Toast.makeText(
getApplicationContext(),
"Reading to close to last reading, replaces last reading", Toast.LENGTH_SHORT).show();
}
}
if (markerArrayList.size() == 8) {
markerArrayList.get(0).remove();
markerArrayList.remove(0);
}
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
if (!initiateApp) {
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Time of reading: " + currentTime);
markerOptions.snippet("co: " + String.valueOf(co_mV) + " mV, " + "no2: " + String.valueOf(no2_mV) + " mV");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);
markerArrayList.add(mCurrLocationMarker);
}
mLastLocation = location;
Log.d("ADebugTag", "Value: " + Double.toString(location.getLatitude()));
Log.d("ADebugTag", "Value: " + Double.toString(location.getLongitude()));
//move map camera
if(initiateApp){
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));
}
boolean contains = mMap.getProjection()
.getVisibleRegion()
.latLngBounds
.contains(latLng);
if(!contains){
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
}
initiateApp = false;
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission(){
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Asking user if explanation is needed
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted. Do the
// contacts-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
// Permission denied, Disable the functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
// other 'case' lines to check for other permissions this app might request.
// You can add here other case statements according to your requirement.
}
}
ublic JSONObject getNewJSON(JSONObject json) {
try {
int humidity = json.getInt("humidity_ppm");
int pressure = json.getInt("pressure_Pa");
int noise = json.getInt("noise_dB");
double lat = mLastLocation.getLatitude();
double lng = mLastLocation.getLongitude();
long time = System.currentTimeMillis() / 1000L;
JSONObject c = new JSONObject();
c.put("time",time);
c.put("lat",lat);
c.put("long",lng);
c.put("humidity",humidity);
c.put("pressure",pressure);
c.put("noise_dB",noise);
return c;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
public class ConnectTask extends AsyncTask<String, String, TcpClient> {
#Override
protected TcpClient doInBackground(String... message) {
//we create a TCPClient object
mTcpClient = new TcpClient(new TcpClient.OnMessageReceived() {
#Override
//here the messageReceived method is implemented
public void messageReceived(String message) {
//this method calls the onProgressUpdate
publishProgress(message);
}
});
mTcpClient.run();
return null;
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
try {
JSONObject parser = new JSONObject(values[0]);
JSONObject d = parser.getJSONObject("d");
JSONObject cloudData = getNewJSON(d);
if (mLastLocation != null) {
newData(d);
getTime();
}
System.out.println(cloudData);
} catch (JSONException e) {
e.printStackTrace();
}
//process server response here....
}
}
You said
When I press back and then resume the map
right? Not closing your app.
Simplest way is to override the onBackPressed method, like this:
#Override
public void onBackPressed() {
moveTaskToBack(true);
}
This won't trigger onDestroy() and onCreate() again, so your would leave your Activity instance unmodified. Simple enough, huh?
You can make a function that populates with fresh data from your server. Then you can call that function as soon as the server sends the JSON data. To answer your question, you simply call the same function in onResume. For more information about activity state read this.
The other approach is to save it in a savedInstanceState bundle and do check in onSaveInstanceState just like this SO accepted answer if that bundle is not null, if so populate the map with the List(last known locations of the markers, if that works with your project). Otherwise just load the map.
I found this answer which provides an elegant one-line solution. This will restore markers when the user rotates the phone, but not when he presses the Back button (I know this is not what OP asked but Google will lead people here)
Add the following in onCreate:
// mapFragment is a SupportMapFragment
mapFragment.setRetainInstance(true);
In manifest file, you can add this line:
<activity android:name=".MapsActivity"
android:configChanges="orientation|screenSize">
It was one of the simplest solution that worked for me in tandem with
#Override
public void onBackPressed() {
moveTaskToBack(true);
}
, and works for simple enough apps, though onSaveInstanceState() method is recommended too. What I found from my research is it's tough to serialize and deserialize marker lists, and onSaveInstanceState() only works with simple objects like strings and such. If anyone found a better solution, please let me know too :)

CameraPosition zoom and target doesn't work in Android 6

I'm doing an app that show some POI on the map after reading a json with this points.
my app work well in android 4.4 but when I run it in android 6 (both emulator and real device), the camera does not zoom at the level I'm setting.
I'm receiving no errors or warning about some deprecated command.
this is the code in the MainActivity
#Override
public void onMapReady(GoogleMap map) {
mapVar = map;
// MapWrapperLayout initialization
final MapWrapperLayout mapWrapperLayout = (MapWrapperLayout) findViewById(R.id.map_relative_layout);
// MapWrapperLayout initialization
mapWrapperLayout.init(map, getPixelsFromDp(this, 39 + 20));
this.infoWindow = (ViewGroup) getLayoutInflater().inflate(R.layout.info_window, null);
this.infoTitle = (TextView) infoWindow.findViewById(R.id.title);
this.infoSnippet = (TextView) infoWindow.findViewById(R.id.snippet);
this.infoButton = (Button) infoWindow.findViewById(R.id.button);
// Setting custom OnTouchListener which deals with the pressed state
// so it shows up
this.infoButtonListener = new OnInfoWindowElemTouchListener(infoButton,
getResources().getDrawable(R.drawable.round_but_green_sel), //btn_default_normal_holo_light
getResources().getDrawable(R.drawable.round_but_red_sel)) //btn_default_pressed_holo_light
{
#Override
protected void onClickConfirmed(View v, Marker marker) {
// Here we can perform some action triggered after clicking the button
//Toast.makeText(MainActivity.this, marker.getTitle() + "'s button clicked!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MainActivity.this, dettaglio.class);
//EditText editText = (EditText) findViewById(R.id.edit_message);
String titolo = marker.getTitle();
String idPOI = allMarkersMapIds.get(marker);
String IMGPOI = allMarkersMapImg.get(marker);
String Desc = allMarkersMapDesc.get(marker);
String idUtentePOI = allMarkersMapidUtente.get(marker);
String idCategoria = allMarkersMapidCategoria.get(marker);
LATLON = marker.getPosition();
Bundle args = new Bundle();
args.putParcelable("coordinatePOI", LATLON);
intent.putExtra("bundle", args);
intent.putExtra(EXTRA_MESSAGE, titolo);
intent.putExtra(EXTRA_ID, idPOI);
intent.putExtra(EXTRA_IMG, IMGPOI);
intent.putExtra(EXTRA_Desc, Desc);
intent.putExtra("IDCATEGORIAPOI", idCategoria);
intent.putExtra("IDUTENTEPOI", idUtentePOI);
startActivity(intent);
}
};
this.infoButton.setOnTouchListener(infoButtonListener);
map.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker marker) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
// Setting up the infoWindow with current's marker info
infoTitle.setText(marker.getTitle());
infoSnippet.setText(marker.getSnippet());
infoButtonListener.setMarker(marker);
// We must call this to set the current marker and infoWindow references
// to the MapWrapperLayout
mapWrapperLayout.setMarkerWithInfoWindow(marker, infoWindow);
return infoWindow;
}
});
/// HERE I CENTER AND ZOOM THE CAMERA
CameraPosition googlePlex = CameraPosition.builder()
.target(new LatLng(latitude, longitude))
.zoom(15)
.bearing(0)
.tilt(45)
.build();
setUpMapIfNeeded(0, ricercaString);
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) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
map.setMyLocationEnabled(true);
map.moveCamera(CameraUpdateFactory.newCameraPosition(googlePlex));
map.animateCamera(CameraUpdateFactory.newCameraPosition(googlePlex), 2000, null);
}
and I'm doing the same thing inside a service that listen for location changes
#Override
public void onLocationChanged(Location location) {
listPOI = MainActivity.getArrayList();
// a bool value to understand if I can go ahead
goAhead = MainActivity.getGoAhead();
namesPOI = MainActivity.getNamePOI();
range = PrefActivity.getRange();
proximity = PrefActivity.getProximity();
//checks whether the user wants to be notified
if(proximity) {
//check if the list of near POI is loaded
if (goAhead) {
if (utility.isNear(location, listPOI, namesPOI, range)) {
POI = utility.getNamePOI();
String msg = "You're near " + POI;
tts1.tts.speak(msg, TextToSpeech.QUEUE_FLUSH, null);
}
}
}
getLocation();
CameraUpdate center = CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(),location.getLongitude()));
MainActivity.mapVar.moveCamera(center);
CameraUpdate zoom = CameraUpdateFactory.zoomTo(15);
MainActivity.mapVar.animateCamera(zoom);
}
But the zoom is still at world level...somebody can figure out why?
Ok, I changed the onMapReady as follows, and now it work.
#Override
public void onMapReady(GoogleMap map) {
mapVar = map;
// MapWrapperLayout initialization
CameraPosition googlePlex = CameraPosition.builder()
.target(new LatLng(latitude, longitude))
.zoom(15)
.bearing(0)
.tilt(45)
.build();
map.animateCamera(CameraUpdateFactory.newCameraPosition(googlePlex), 2000, null);
final MapWrapperLayout mapWrapperLayout = (MapWrapperLayout) findViewById(R.id.map_relative_layout);
// MapWrapperLayout initialization
mapWrapperLayout.init(map, getPixelsFromDp(this, 39 + 20));
this.infoWindow = (ViewGroup) getLayoutInflater().inflate(R.layout.info_window, null);
this.infoTitle = (TextView) infoWindow.findViewById(R.id.title);
this.infoSnippet = (TextView) infoWindow.findViewById(R.id.snippet);
this.infoButton = (Button) infoWindow.findViewById(R.id.button);
// Setting custom OnTouchListener which deals with the pressed state
// so it shows up
this.infoButtonListener = new OnInfoWindowElemTouchListener(infoButton,
getResources().getDrawable(R.drawable.round_but_green_sel), //btn_default_normal_holo_light
getResources().getDrawable(R.drawable.round_but_red_sel)) //btn_default_pressed_holo_light
{
#Override
protected void onClickConfirmed(View v, Marker marker) {
// Here we can perform some action triggered after clicking the button
//Toast.makeText(MainActivity.this, marker.getTitle() + "'s button clicked!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MainActivity.this, dettaglio.class);
//EditText editText = (EditText) findViewById(R.id.edit_message);
String titolo = marker.getTitle();
String idPOI = allMarkersMapIds.get(marker);
String IMGPOI = allMarkersMapImg.get(marker);
String Desc = allMarkersMapDesc.get(marker);
String idUtentePOI = allMarkersMapidUtente.get(marker);
String idCategoria = allMarkersMapidCategoria.get(marker);
LATLON = marker.getPosition();
Bundle args = new Bundle();
args.putParcelable("coordinatePOI", LATLON);
intent.putExtra("bundle", args);
intent.putExtra(EXTRA_MESSAGE, titolo);
intent.putExtra(EXTRA_ID, idPOI);
intent.putExtra(EXTRA_IMG, IMGPOI);
intent.putExtra(EXTRA_Desc, Desc);
intent.putExtra("IDCATEGORIAPOI", idCategoria);
intent.putExtra("IDUTENTEPOI", idUtentePOI);
startActivity(intent);
}
};
this.infoButton.setOnTouchListener(infoButtonListener);
map.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker marker) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
// Setting up the infoWindow with current's marker info
infoTitle.setText(marker.getTitle());
infoSnippet.setText(marker.getSnippet());
infoButtonListener.setMarker(marker);
// We must call this to set the current marker and infoWindow references
// to the MapWrapperLayout
mapWrapperLayout.setMarkerWithInfoWindow(marker, infoWindow);
return infoWindow;
}
});
setUpMapIfNeeded(0, ricercaString);
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) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
map.setMyLocationEnabled(true);
}
1.
Instead of animateCamera > newCameraPosition use moveCamera > newLatLngZoom
Replace
CameraPosition cameraPosition = new CameraPosition.Builder().target(location).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
with
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(location, 9));
Use CancelableCallback in animateCamera (kind of work around)
.
googleMap.animateCamera(CameraUpdateFactory.newLatLngBounds(latLngBounds, 5), new GoogleMap.CancelableCallback() {
#Override
public void onFinish() {
CameraUpdate zout = CameraUpdateFactory.zoomBy(-3f);
googleMap.animateCamera(zout);
}
#Override
public void onCancel() {
}
});

Plot Route on Google Maps Fragment via URL

So I have looked around for examples of plotting routes on Google maps. However, my obstacle is that I have to go to url/route.coords in order to get the lat and lng for the route. When I go to that url manually it downloads a text file with all the route information. So if anyone could help me as to where to start that would be greatly appreciated. I already have the map showing along with a dot for your current location along with some other classes outlined. My end goal is to plot a different colored route for every drive, each drive has their specific URL.
Fragment for where I am showing my Google Maps:
public class ThirdFragment extends Fragment implements OnMapReadyCallback {
View myView;
private GoogleMap mMap;
MapFragment mapFrag;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.third_layout, container, false);
return myView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mapFrag = (MapFragment) getChildFragmentManager().findFragmentById(R.id.map);
mapFrag.getMapAsync(this);
//mapFrag.onResume();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
Criteria criteria = new Criteria();
LocationManager locationManager = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
String provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
double lat = location.getLatitude();
double lng = location.getLongitude();
LatLng coordinate = new LatLng(lat, lng);
CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(coordinate, 13);
mMap.animateCamera(yourLocation);
} else {
final AlertDialog alertDialogGPS = new AlertDialog.Builder(getActivity()).create();
alertDialogGPS.setTitle("Info");
alertDialogGPS.setMessage("Looks like you have not given GPS permissions. Please give GPS permissions and return back to the app.");
alertDialogGPS.setIcon(android.R.drawable.ic_dialog_alert);
alertDialogGPS.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intentSettings = new Intent(Settings.ACTION_APPLICATION_SETTINGS);
startActivity(intentSettings);
alertDialogGPS.dismiss();
}
});
alertDialogGPS.show();
}
}
#Override
public void onResume() {
super.onResume();
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mapFrag.getMapAsync(this);
}
else {
}
}
}
RouteCoord.java
public class RouteCoord {
private String lat, dist, lng, speed, index;
public String getLat() {
return lat;
}
public void setLat(String lat) {this.lat = lat;}
public String getLng(){return lng;}
public void setLng(String lng) {this.lng = lng;}
}
RouteAdapter.java
public class RouteAdapter extends ArrayAdapter<Map.Entry> {
private final Activity context;
// you may need to change List to something else (whatever is returned from drives.entrySet())
private final List<Map.Entry> drives;
public static String DriveURL;
public static String routeLat;
public static String routeLng;
SharedPreferences sharedPref;
// may also need to change List here (above comment)
public RouteAdapter(Activity context, List<Map.Entry> drives) {
super(context, R.layout.drive_url_list, drives);
this.context = context;
this.drives = drives;
sharedPref = context.getPreferences(Context.MODE_PRIVATE);
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.third_layout, null, true);
Map.Entry drive = this.drives.get(position);
// position is the index of the drives.entrySet() array
int driveNum = position + 1;
// need to import your Route class
Route route = (Route) drive.getValue();
RouteCoord routeCoord = (RouteCoord) drive.getValue();
routeLat = routeCoord.getLat();
routeLng = routeCoord.getLng();
// need to import your URL class
DriveURL = route.getUrl();
return rowView;
}
}
You need to draw a Polyline on the Google Map using the coordinates of the route.
See below sample code:
/**
* To show map with this activity add ORIGIN, DESTINATION lat double arrays in
* intent.
*
* </br> For specifying origin, put latitude and longitude in an array of double
* with key = {#link #ORIGIN} in the intent </br >For specifying destination,
* put latitude and longitude in an array of double with key =
* {#link #DESTINATION} in the intent
*
* #author Shridutt.Kothari
*
*/
public class MapsActivity extends BaseActivity {
private static final String TAG = "MapsActivity";
/**
* String key for specifying array of long containing origin latitude and
* longitude .
*/
public static final String ORIGIN = "ORIGIN";
private double[] destinationLocation;
private GoogleMap map;
private PathUpdateReceiver pathUpdateReceiver;
private PolylineOptions lineOptions;
private Marker marker;
private MarkerOptions ambulanceMarkerOption;
private Polyline polyline;
private List<LatLng> points;
private static final int ZOOM_LEVEL = 15;
private static final int POLYLINE_WIDTH = 5;
private static final String AMBULANCE_MARKER_NAME = "Ambulance";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
// Intent launchIntent = getIntent();
// originLocation = new double[2];
// originLocation = launchIntent.getDoubleArrayExtra(ORIGIN);
// originLocation[0] = 28.628525;
// originLocation[1] = 77.22219016666666;
destinationLocation = new double[2];
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
if (null == map) {
try {
MapsInitializer.initialize(getApplicationContext());
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"Google play services not available, can't show map!",
Toast.LENGTH_LONG).show();
e.printStackTrace();
this.finish();
}
}
}
#Override
protected void onResume() {
super.onResume();
if (null == pathUpdateReceiver) {
pathUpdateReceiver = new PathUpdateReceiver();
}
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(AppConstants.VEHICLE_DATA_SAMPLE_ID);
registerReceiver(pathUpdateReceiver, intentFilter);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(pathUpdateReceiver);
}
/**
* PathUpdate
*
*
*/
private class PathUpdateReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (map != null
&& intent.getAction().equalsIgnoreCase(
AppConstants.VEHICLE_DATA_SAMPLE_ID)) {
map.getUiSettings().setZoomControlsEnabled(true);
map.getUiSettings().setTiltGesturesEnabled(true);
map.getUiSettings().setAllGesturesEnabled(true);
VehicleDataSample vehicleDataSample = ((GoldenHourTrackerApp) getApplication()).getVehicleDataSample();
destinationLocation[0] = vehicleDataSample.getLatitude();
destinationLocation[1] = vehicleDataSample.getLongitude();
Log.e(TAG, "received location update:"+destinationLocation[0]+", "+destinationLocation[1]);
LatLng newPoint = new LatLng(destinationLocation[0],
destinationLocation[1]);
if (null != destinationLocation) {
map.setTrafficEnabled(false);
map.setBuildingsEnabled(true);
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
LatLng originlatlng = new LatLng(destinationLocation[0],
destinationLocation[1]);
map.moveCamera(CameraUpdateFactory.newLatLngZoom(
originlatlng, ZOOM_LEVEL));
-#SuppressWarnings("unused")
MarkerOptions traumaLoacationMarkerOption = new MarkerOptions()
.position(originlatlng)
.title(TRAUMA_LOCATION_MARKER_NAME)
.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_RED));
if (ambulanceMarkerOption == null) {
ambulanceMarkerOption = new MarkerOptions()
.position(originlatlng)
.title(AMBULANCE_MARKER_NAME)
.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
// TODO: Currently Not adding
// TRAUMA_LOCATION_MARKER_NAME on Map
// map.addMarker(traumaLoacationMarkerOption);
marker = map.addMarker(ambulanceMarkerOption);
marker.showInfoWindow();
}
if (null == lineOptions) {
lineOptions = new PolylineOptions();
lineOptions.add(newPoint);
// A 5 width Polyline
lineOptions.width(POLYLINE_WIDTH);
lineOptions.color(context.getResources().getColor(
R.color.blue));
polyline = map.addPolyline(lineOptions);
}
marker.setPosition(newPoint);
marker.setVisible(true);
marker.showInfoWindow();
map.animateCamera(CameraUpdateFactory.newLatLngZoom(
newPoint, ZOOM_LEVEL));
points = polyline.getPoints();
points.add(newPoint);
polyline.setPoints(points);
}
}
}
}
}

Categories

Resources