I'm trying to display heatmap points in android using google maps utility library, nothing is displayed on the map. I don't know if I need something else, I've looked at examples but in my case it doesn't work. I'm using fragments.
public class MapFragment extends Fragment {
MapView mMapView;
private GoogleMap googleMap;
private HeatmapTileProvider mProvider;
protected LatLng mCenterLocation = new LatLng( 39.7392, -104.9903 );
public MapFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_map, container, false);
mMapView = (MapView) rootView.findViewById(R.id.mapView);
mMapView.onCreate(savedInstanceState);
mMapView.onResume(); // needed to get the map to display immediately
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
mMapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
// For showing a move to my location button
if (ActivityCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), 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;
}
googleMap.setMyLocationEnabled(true);
// For dropping a marker at a point on the Map
LatLng colorado = new LatLng(39.7392, -104.9903);
googleMap.addMarker(new MarkerOptions().position(colorado).title("Marker Title").snippet("Marker Description"));
// For zooming automatically to the location of the marker
CameraPosition cameraPosition = new CameraPosition.Builder().target(colorado).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
addHeatMap();
}
});
return rootView;
}
public void addHeatMap(){
ArrayList<LatLng> locations = generateLocations();
mProvider = new HeatmapTileProvider.Builder().data(locations).build();
mProvider.setRadius(HeatmapTileProvider.DEFAULT_RADIUS );
googleMap.addTileOverlay(new TileOverlayOptions().tileProvider(mProvider));
}
private ArrayList<LatLng> generateLocations() {
ArrayList<LatLng> locations = new ArrayList<LatLng>();
double lat;
double lng;
Random generator = new Random();
for (int i = 0; i < 1000; i++) {
lat = generator.nextDouble() / 3;
lng = generator.nextDouble() / 3;
if (generator.nextBoolean()) {
lat = -lat;
}
if (generator.nextBoolean()) {
lng = -lng;
}
locations.add(new LatLng(mCenterLocation.latitude + lat, mCenterLocation.longitude + lng));
}
return locations;
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
}
Checking the Heatmaps guide, I don't see any issues about it. Try to call clearTileCache(), its indicated in its API reference that you should call it after setRadius.
Related
Draw Polyline on google map while Running /Drawing
I'm Creating a where the users can track there a path from where to where he just ran. I have tried Following code it's working but while running it getting start to lagging can anyone tell me where I doing wrong.
To draw polyline I'm refreshing map after some interval
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {
private static final int MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 5445;
private GoogleMap googleMap;
private FusedLocationProviderClient fusedLocationProviderClient;
private Marker currentLocationMarker;
private Location currentLocation;
private boolean firstTimeFlag = true;
private ArrayList<LatLng> points =new ArrayList<>(); //added
Polyline line; //added
/* private final View.OnClickListener clickListener = view -> {
if (view.getId() == R.id.currentLocationImageButton && googleMap != null && currentLocation != null)
animateCamera(currentLocation);
};
*/
private final LocationCallback mLocationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
if (locationResult.getLastLocation() == null)
return;
currentLocation = locationResult.getLastLocation();
if (firstTimeFlag && googleMap != null) {
animateCamera(currentLocation);
firstTimeFlag = false;
}
showMarker(currentLocation);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
supportMapFragment.getMapAsync(this);
// findViewById(R.id.currentLocationImageButton).setOnClickListener(clickListener);
}
#Override
public void onMapReady(GoogleMap googleMap) {
this.googleMap = googleMap;
}
private void startCurrentLocationUpdates() {
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(3000);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
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) {
ActivityCompat.requestPermissions(MapsActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
return;
}
}
fusedLocationProviderClient.requestLocationUpdates(locationRequest, mLocationCallback, Looper.myLooper());
}
private boolean isGooglePlayServicesAvailable() {
GoogleApiAvailability googleApiAvailability = GoogleApiAvailability.getInstance();
int status = googleApiAvailability.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status)
return true;
else {
if (googleApiAvailability.isUserResolvableError(status))
Toast.makeText(this, "Please Install google play services to use this application", Toast.LENGTH_LONG).show();
}
return false;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION) {
if (grantResults[0] == PackageManager.PERMISSION_DENIED)
Toast.makeText(this, "Permission denied by uses", Toast.LENGTH_SHORT).show();
else if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
startCurrentLocationUpdates();
}
}
private void animateCamera(#NonNull Location location) {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(getCameraPositionWithBearing(latLng)));
}
#NonNull
private CameraPosition getCameraPositionWithBearing(LatLng latLng) {
return new CameraPosition.Builder().target(latLng).zoom(16).build();
}
private void showMarker(#NonNull Location currentLocation) {
LatLng latLng = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
if (currentLocationMarker != null){
System.out.println("LastMArkerPostion" + currentLocationMarker.getPosition());
points.add(currentLocationMarker.getPosition());
currentLocationMarker.remove();
}
PolylineOptions options = new PolylineOptions();
for (int i = 0 ; i<points.size() ; i++ ){
options.add(points.get(i)).width(15).color(Color.BLUE).geodesic(true);
googleMap.addPolyline(options);
}
Drawable vectorDrawable = ResourcesCompat.getDrawable(getResources(), R.drawable.ic_green_car_marker, null);
Bitmap bit = Bitmap.createBitmap(vectorDrawable.getIntrinsicWidth(),
vectorDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bit);
vectorDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
vectorDrawable.draw(canvas);
currentLocationMarker = googleMap.addMarker(new MarkerOptions().icon( BitmapDescriptorFactory.fromBitmap(bit)).position(latLng));
}
#Override
protected void onStop() {
super.onStop();
if (fusedLocationProviderClient != null)
fusedLocationProviderClient.removeLocationUpdates(mLocationCallback);
}
#Override
protected void onResume() {
super.onResume();
if (isGooglePlayServicesAvailable()) {
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
startCurrentLocationUpdates();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
fusedLocationProviderClient = null;
googleMap = null;
}
}
Thanks in advance
Solution
After so many research I found the solution on a GitHub repository
I have made some changes in original code
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private static final String TAG = "MapsActivity";
public GoogleMap mMap;
private ArrayList<LatLng> points;
Polyline line;
Marker now;
double lat1;
double lon1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
points = new ArrayList<LatLng>();
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#SuppressLint("MissingPermission")
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (!mMap.isMyLocationEnabled())
mMap.setMyLocationEnabled(true);
LocationManager lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
Location myLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (myLocation == null) {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
String provider = lm.getBestProvider(criteria, true);
myLocation = lm.getLastKnownLocation(provider);
}
if (myLocation != null) {
LatLng userLocation = new LatLng(myLocation.getLatitude(), myLocation.getLongitude());
lat1=myLocation.getLatitude();
lon1=myLocation.getLongitude();
mMap.addMarker(new MarkerOptions()
.position(userLocation)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE))
.title("Welcome ")
.snippet("Latitude:"+lat1+",Longitude:"+lon1)
);
Log.v(TAG, "Lat1=" + lat1);
Log.v(TAG, "Long1=" + lon1);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 20), 1500, null);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000,0, new LocationListener() {
#Override
public void onLocationChanged(Location myLocation) {
// Getting latitude of the current location
double latitude = myLocation.getLatitude();
// Getting longitude of the current location
double longitude = myLocation.getLongitude();
// Creating a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
//Adding new marker
/* now = mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))
.position(latLng).title("New")
.snippet("Latitude:"+lat1+",Longitude:"+lon1)
);*/
// Showing the current location in Google Map
// mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
// mMap.animateCamera(CameraUpdateFactory.zoomTo(20));
//Draw polyline
drawPolygon(latitude, longitude);
// Toast.makeText(MapsActivity.this, String.valueOf(latitude)+String.valueOf(longitude), Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
// TODO Auto-generated method stub
}
});
}
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, 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;
}
mMap.getUiSettings().setZoomControlsEnabled(true);
}
private void drawPolygon( double latitude, double longitude) {
List<LatLng> polygon = new ArrayList<>();
//old lat and long
polygon.add(new LatLng(lat1, lon1));
//new lat and long
polygon.add(new LatLng(latitude,longitude));
mMap.addPolygon(new PolygonOptions()
.addAll(polygon)
.strokeColor(Color.parseColor("#03A9F4"))
.strokeWidth(15)
.fillColor(Color.parseColor("#B3E5FC"))
);
lat1=latitude;
lon1=longitude;
}
}
Full code available on
Github
I am trying to list all the places according to the query type specified by the user. The app will show the map with markers of the places that are returned from the API call.
private GoogleMap mMap;
private GoogleApiClient mGoogleApiClient;
static String itemSelected;
PendingResult<PlaceLikelihoodBuffer> result;
static int clicked;
CharSequence[] items = {"accounting", "airport", "amusement_park", "aquarium", "art_gallery","atm","bakery","bank","bar","beauty_salon","bicycle_store","book_store","bowling_alley","bus_station","cafe"};
#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.
final SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
mGoogleApiClient = new GoogleApiClient
.Builder(this)
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.enableAutoManage(this,this)
.build();
final AlertDialog.Builder ad = new AlertDialog.Builder(this);
ad.setTitle("Pick a place")
.setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Log.d("Demo", "Selected :" + items[which]);
clicked = which;
}
})
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#TargetApi(Build.VERSION_CODES.M)
#Override
public void onClick(DialogInterface dialog, int which) {
itemSelected = String.valueOf(items[clicked]);
Log.d("demo",itemSelected);
mapFragment.getMapAsync(MapsActivity.this);
}
})
.setCancelable(false);
AlertDialog alert = ad.create();
ad.show();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode)
{
case 100:
{
if(grantResults[0]== PackageManager.PERMISSION_GRANTED)
{
result.setResultCallback(new ResultCallback<PlaceLikelihoodBuffer>() {
#Override
public void onResult(#NonNull PlaceLikelihoodBuffer placeLikelihoods) {
Log.d("demo",placeLikelihoods.getStatus()+"");
}
});
}
else
{
Toast.makeText(this,"Permission denied by the user", Toast.LENGTH_LONG).show();
}
}
}
}
/**
* 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;
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
// TODO: Consider calling
MapsActivity.this.requestPermissions(new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},100);
// 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;
}
result= Places.PlaceDetectionApi.getCurrentPlace(mGoogleApiClient,null);
final PendingResult<PlaceLikelihoodBuffer> pbuff = Places.PlaceDetectionApi.getCurrentPlace(mGoogleApiClient,null);
pbuff.setResultCallback(new ResultCallback<PlaceLikelihoodBuffer>() {
#Override
public void onResult(#NonNull PlaceLikelihoodBuffer placeLikelihoods) {
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for(PlaceLikelihood placeLikelihood : placeLikelihoods){
if (placeLikelihood.getPlace().getPlaceTypes().contains(itemSelected)){
mMap.addMarker(new MarkerOptions().position(placeLikelihood.getPlace().getLatLng()).title(placeLikelihood.getPlace().getName().toString()).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
builder.include(placeLikelihood.getPlace().getLatLng());
}
else{
mMap.addMarker(new MarkerOptions().position(placeLikelihood.getPlace().getLatLng()).title(placeLikelihood.getPlace().getName().toString()));
builder.include(placeLikelihood.getPlace().getLatLng());
}
}
placeLikelihoods.release();
LatLngBounds bounds = builder.build();
int padding = 10; // offset from edges of the map in pixels
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, padding);
mMap.animateCamera(cu);
//mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), 10));
// Remove listener to prevent position reset on camera move.
//mMap.setOnCameraChangeListener(null);
// LatLngBounds.Builder bounds = new LatLngBounds.Builder();
// for (DataItem location : mUserLocations.keySet()) {
// bounds.include(new LatLng(
// Double.parseDouble(location.mData
// .get("latitude")), Double
// .parseDouble(location.mData
// .get("longitude"))));
// }
//
// LatLngBounds mapBounds;
// for (DataItem location : result. ) {
// if (mapBounds==null) {
// LatLng point = new LatLng(Double.parseDouble(location.pbuff.get("latitude")), Double.parseDouble(location.mData.get("longitude")))
// mapBounds =new LatLngBounds(point, point);
// } else {
// mapBounds = mapBounds.including(new LatLng(Double.parseDouble(location.mData.get("latitude")), Double.parseDouble(location.mData.get("longitude"))));
// }
// }
}
});
// 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"));
// mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}
But the app crashes with the following error:
java.lang.IllegalStateException: no included points
at com.google.android.gms.common.internal.zzaa.zza(Unknown Source)
at
com.google.android.gms.maps.model.LatLngBounds$Builder.build(Unknown
Source).
I have tried various other links posted on SO, but nothing seems to work. Please help. This is my first question on SO, please let me know if I have done any mistakes.
I am using google play service for a running app i am making. I am getting the problem that onlocationchanged is not being called. First i though it was the android device that was not working but after testing it with GPS test it seems the device was working as it should. So it must be my code. Onlocationchanged is just not being called by the gps_provider but when i use network_provider it is working but the updates are so slow and in accurate that you can't build a sport runner app with it.
This is my code, what should i do to fix this?
this is in my manifest
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="com.befitdonate.befitdonate.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_GPS" />
<uses-permission android:name="android.permission.ACCESS_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_ASSISTED_GPS" />
This is my fragment i am using to track the users route on the map.
public class WorkoutActivity extends Fragment implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
private static String TAG = WorkoutActivity.class.getSimpleName();
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private LocationRequest mLocationRequest;
MapView mapView;
GoogleMap map;
private GoogleApiClient mGoogleApiClient;
private SharedPreferences preferenceSettings;
private SharedPreferences.Editor preferenceEditor;
private static final int PREFERENCE_MODE_PRIVATE = 0;
private static final String PREF_NAME = "UserDetails";
public static final String POST_USEREMAIL = "username";
MainActivity mainactivity;
String emailUser, workoutType;
Button stopWorkout, startWorkout;
TextView speed, info;
ImageView workoutImage;
LinearLayout mapLayout, startWorkoutLayout;
Double currentLat, currentLong;
Double Lat, Longi;
String latLong = "No Location Found!!!";
LocationManager lManager;
final private int REQUEST_CODE_ASK_PERMISSIONS = 123;
//counter that is incremented every time a new position is received, used to calculate average speed
int counter = 0;
//objects to store values for current and average speed
protected double currentSpeed;
protected double kmphSpeed;
protected double avgSpeed;
protected double avgKmph;
protected double totalSpeed;
protected double totalKmph;
ArrayList<LatLng> polylines;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
preferenceSettings = this.getActivity().getSharedPreferences(PREF_NAME, PREFERENCE_MODE_PRIVATE);
preferenceEditor = preferenceSettings.edit();
emailUser = preferenceSettings.getString("Email", null);
Log.d("Saved user email:", "" + emailUser);
Bundle bundle = this.getArguments();
if (bundle != null) {
workoutType = bundle.getString("workoutType");
}
mGoogleApiClient = new GoogleApiClient.Builder(this.getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
// Create the LocationRequest object
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(1 * 1000) // 5 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_workout, container, false);
mapView = (MapView) view.findViewById(R.id.mapview);
stopWorkout = (Button) view.findViewById(R.id.stopWorkout);
startWorkout = (Button) view.findViewById(R.id.startWorkout);
startWorkoutLayout = (LinearLayout) view.findViewById(R.id.startWorkoutLayout);
mapLayout = (LinearLayout) view.findViewById(R.id.mapLayout);
workoutImage = (ImageView) view.findViewById(R.id.workoutImage);
speed = (TextView) view.findViewById(R.id.speed);
info = (TextView) view.findViewById(R.id.info);
mapView.onCreate(savedInstanceState);
mainactivity = (MainActivity )getActivity();
mainactivity.menuButton.setVisibility(View.GONE);
mainactivity.mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
mainactivity.pageTitle.setText("Workout");
mapLayout.setVisibility(View.GONE);
polylines = new ArrayList<LatLng>();
// Gets to GoogleMap from the MapView and does initialization stuff
map = mapView.getMap();
map.getUiSettings().setMyLocationButtonEnabled(false);
map.setMyLocationEnabled(true);
// Needs to call MapsInitializer before doing any CameraUpdateFactory calls
MapsInitializer.initialize(this.getActivity());
stopWorkout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectOption();
}
});
workoutType = "walking";
startWorkout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mapLayout.setVisibility(View.VISIBLE);
startWorkoutLayout.setVisibility(View.GONE);
}
});
if(workoutType.matches("running")){
Picasso.with(this.getActivity())
.load(R.drawable.newrun)
.fit()
.centerCrop()
.into(workoutImage);
}
if(workoutType.matches("cycling")){
Picasso.with(this.getActivity())
.load(R.drawable.newcycling)
.fit()
.centerCrop()
.into(workoutImage);
}
if(workoutType.matches("walking")){
Picasso.with(this.getActivity())
.load(R.drawable.newwalk)
.fit()
.centerCrop()
.into(workoutImage);
}
return view;
}
#Override
public void onDestroy() {
super.onDestroy();
mainactivity.mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
public void onResume() {
super.onResume();
setUpMapIfNeeded();
mapView.onResume();
mGoogleApiClient.connect();
}
#Override
public void onPause() {
super.onPause();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
//DO WHATEVER YOU WANT WITH GOOGLEMAP
map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
map.setMyLocationEnabled(false);
map.setTrafficEnabled(false);
map.setIndoorEnabled(true);
map.setBuildingsEnabled(true);
map.getUiSettings().setZoomControlsEnabled(true);
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
Log.d(TAG, "Location update running");
handleNewLocation(location);
}
public void selectOption() {
final CharSequence[] items = { "Workout Opslaan", "Afbreken", "Sluiten" };
AlertDialog.Builder builder = new AlertDialog.Builder(WorkoutActivity.this.getActivity());
builder.setTitle("Workout opties");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Workout Opslaan")) {
} else if (items[item].equals("Afbreken")) {
mapView.onDestroy();
mainactivity.mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
mainactivity.menuButton.setVisibility(View.VISIBLE);
if (mGoogleApiClient.isConnected()) {
onDestroy();
}
Fragment fragment = new HomePage();
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.mainContent, fragment)
.commit();
} else if (items[item].equals("Sluiten")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
Log.i(TAG, "Location services connected.");
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
else {
handleNewLocation(location);
};
}
#Override
public void onConnectionSuspended(int i) {
Log.i(TAG, "Location services suspended. Please reconnect.");
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(this.getActivity(), CONNECTION_FAILURE_RESOLUTION_REQUEST);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
} else {
Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
}
}
private void handleNewLocation(Location location) {
Log.d(TAG, location.toString());
double currentLatitude = location.getLatitude();
double currentLongitude = location.getLongitude();
Lat = location.getLatitude();
Longi = location.getLongitude();
LatLng latLng = new LatLng(currentLatitude, currentLongitude);
CameraUpdate zoom=CameraUpdateFactory.zoomTo(17);
map.moveCamera(CameraUpdateFactory.newLatLng(latLng));
map.animateCamera(zoom);
counter++;
//current speed of the gps device
currentSpeed = round(location.getSpeed(),3, BigDecimal.ROUND_HALF_UP);
kmphSpeed = round((currentSpeed*3.6),3,BigDecimal.ROUND_HALF_UP);
//all speeds added together
totalSpeed = totalSpeed + currentSpeed;
totalKmph = totalKmph + kmphSpeed;
//calculates average speed
avgSpeed = round(totalSpeed/counter,3,BigDecimal.ROUND_HALF_UP);
avgKmph = round(totalKmph/counter,3,BigDecimal.ROUND_HALF_UP);
//gets position
currentLatitude = round(((double) (location.getLatitude())),3,BigDecimal.ROUND_HALF_UP);
currentLongitude = round(((double) (location.getLongitude())),3,BigDecimal.ROUND_HALF_UP);
String infoDetails = "Afstand: "+" | Tijd: ";
String updateSpeed = String.valueOf(kmphSpeed);
Log.d(TAG, updateSpeed.toString());
//info.setText();
speed.setText("Snelheid: "+updateSpeed+" km/hr");
buildPolyline();
}
//Method to round the doubles to a max of 3 decimal places
public static double round(double unrounded, int precision, int roundingMode)
{
BigDecimal bd = new BigDecimal(unrounded);
BigDecimal rounded = bd.setScale(precision, roundingMode);
return rounded.doubleValue();
}
public void buildPolyline(){
Log.d(TAG,"Adding polyline" );
LatLng polyline;
polyline = new LatLng(Lat, Longi);
polylines.add(polyline);
Log.d("Locations Array", ""+polylines);
map.addPolyline(new PolylineOptions().addAll(polylines).width(6.0f).color(Color.BLUE));
//map.moveCamera(CameraUpdateFactory.newLatLngZoom(Start, 14));
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (map == null) {
// Try to obtain the map from the SupportMapFragment.
map = ((SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.mapview))
.getMap();
// Check if we were successful in obtaining the map.
if (map != null) {
}
}
}
}
I have spend about a week trying several solution but still stuck with this problem. I need an accurate way to track the route of the runner. I can't find any sport app samples, but enough other location samples but nothing seems to be working. I hope someone can help me with this.
Thanks
you have to use Location manager and register for location updates.
Try adding this code:
protected LocationManager locationManager;
in onCreate() method call registerLocationUpdates();
void registerLocationUpdates() {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_HIGH);
locationManager = (LocationManager)getActivity().getSystemService(LOCATION_SERVICE);
provider = locationManager.getBestProvider(criteria, true);
// Cant get a hold of provider
if (provider == null) {
Log.v(TAG, "Provider is null");
showNoProvider();
return;
} else {
Log.v(TAG, "Provider: " + provider);
}
locationManager.requestLocationUpdates(provider, 0, 0, this);
}
Using Default Google Maps Activity from Android Studio and want to use MY Location displayed on a marker on a map plus the my location blue google button which is usually located bottom right.
Have looked over hundreds of examples and code and nothing is working.
package com.example.br.nightlyfegooglemap;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,OnInfoWindowClickListener,
OnMyLocationChangeListener, GoogleMap.OnMyLocationChangeListener {
private GoogleMap mMap;
protected GoogleApiClient mGoogleApiClient;
private static final String STATE_IN_PERMISSION="inPermission";
private static final int REQUEST_PERMS=1337;
private boolean needsInit=false;
private boolean isInPermission=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
if (savedInstanceState==null) {
needsInit=true;
}
else {
isInPermission=
savedInstanceState.getBoolean(STATE_IN_PERMISSION, false);
}
onCreateForRealz(canGetLocation());
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(STATE_IN_PERMISSION, isInPermission);
}
#Override
public void onRequestPermissionsResult(int requestCode,
String[] permissions,
int[] grantResults) {
isInPermission=false;
if (requestCode==REQUEST_PERMS) {
if (canGetLocation()) {
onCreateForRealz(true);
}
else {
finish(); // denied permission, so we're done
}
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
if (needsInit) {
CameraUpdate center=CameraUpdateFactory.newLatLng(new LatLng(40.76793169992044,-73.98180484771729));
CameraUpdate zoom=CameraUpdateFactory.zoomTo(15);
mMap.moveCamera(center);
mMap.animateCamera(zoom);
}
mMap.setInfoWindowAdapter(new PopupAdapter(getLayoutInflater()));
mMap.setOnInfoWindowClickListener(this);
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationChangeListener(this);
}
public void onInfoWindowClick(Marker marker) {
Toast.makeText(this, marker.getTitle(), Toast.LENGTH_LONG).show();
}
#Override
public void onMyLocationChange(Location lastKnownLocation) {
Log.d(getClass().getSimpleName(),
String.format("%f:%f", lastKnownLocation.getLatitude(),
lastKnownLocation.getLongitude()));
}
private void onCreateForRealz(boolean canGetLocation) {
if (canGetLocation) {
if (readyToGo()) {
setContentView(R.layout.activity_maps);
MapFragment mapFrag=
(MapFragment)getFragmentManager().findFragmentById(
R.id.map);
mapFrag.getMapAsync(this);
}
}
else if (!isInPermission) {
isInPermission=true;
ActivityCompat.requestPermissions(this,
new String[] {Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_PERMS);
}
}
private void addMarker(GoogleMap map, double lat, double lon,
int title, int snippet) {
map.addMarker(new MarkerOptions().position(new LatLng(lat, lon))
.title(getString(title))
.snippet(getString(snippet)));
}
private boolean canGetLocation() {
return(ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)==
PackageManager.PERMISSION_GRANTED);
}
}
ERRORS
//CANNOT RESOLVE SYMBOLS FOR THESE
OnInfoWindowClickListener,
OnMyLocationChangeListener
new PopupAdapter
readyToGo
//REQUIRES PERMISSION
mMap.setMyLocationEnabled(true);
//DEPRECATED
mMap.setOnMyLocationChangeListener(this);
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{
}