This question already has answers here:
How can I show current location on a Google Map on Android Marshmallow?
(3 answers)
Closed 5 years ago.
My code create a route between two points on the map in the coordinates I'm trying to get past the coodernada from my current location to the fromPosition, using the low code. But he is giving 0,0 in Log.i;
double lat;
double lng;
LatLng fromPosition = new LatLng(lat, lng);
LatLng toPosition = new LatLng(-5.082434, -42.807364);
But I need the co-penned fromPosition to be my current position.
Thank you for any help.
public class MapsActivity2 extends FragmentActivity {
private GoogleMap map;
double lat;
double lng;
LatLng fromPosition = new LatLng(lat, lng);
LatLng toPosition = new LatLng(-5.082434, -42.807364);
ArrayList<LatLng> directionPoint;
Marker mPositionMarker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps2);
initializeMap();
Log.i("david", "LATLNG= " + fromPosition);
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
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;
}
long tempo = 1000; //5 minutos
float distancia = 1; // 30 metros
map.setMyLocationEnabled(true);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER , tempo , distancia, new LocationListener() {
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
#Override
public void onProviderEnabled(String arg0) {
Toast.makeText(getApplicationContext(), "GPS Habilitado", Toast.LENGTH_LONG).show();
}
#Override
public void onProviderDisabled(String arg0) {
Toast.makeText(getApplicationContext(), "GPS Desabilitado", Toast.LENGTH_LONG).show();
}
#Override
public void onLocationChanged(Location location) {
if (location == null)
return;
map.setMyLocationEnabled(true);
lat = location.getLatitude();
lng = location.getLongitude();
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new
LatLng(lat, lng), 16));
if (mPositionMarker == null) {
mPositionMarker = map.addMarker(new MarkerOptions()
.flat(true)
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.car))
.anchor(0.5f, 0.5f)
.position(
new LatLng(location.getLatitude(), location
.getLongitude())));
}
animateMarker(mPositionMarker, location); // Helper method for smooth
// animation
map.animateCamera(CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude())));
}
public void animateMarker(final Marker marker, final Location location) {
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
final LatLng startLatLng = marker.getPosition();
final double startRotation = marker.getRotation();
final long duration = 500;
final Interpolator interpolator = new LinearInterpolator();
handler.post(new Runnable() {
#Override
public void run() {
long elapsed = SystemClock.uptimeMillis() - start;
float t = interpolator.getInterpolation((float) elapsed
/ duration);
double lng = t * location.getLongitude() + (1 - t)
* startLatLng.longitude;
double lat = t * location.getLatitude() + (1 - t)
* startLatLng.latitude;
float rotation = (float) (t * location.getBearing() + (1 - t)
* startRotation);
marker.setPosition(new LatLng(lat, lng));
marker.setRotation(rotation);
if (t < 1.0) {
// Post again 16ms later.
handler.postDelayed(this, 16);
}
}
});
}
}, null);
}
private void initializeMap() {
if (map == null) {
map = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
new WebserviceTask(this).execute();
}
}
public void setDirectionPoints(ArrayList<LatLng> result) {
directionPoint = new ArrayList<LatLng>();
directionPoint = result;
}
protected void onResume() {
super.onResume();
initializeMap();
}
public class WebserviceTask extends
AsyncTask<Void, Void, ArrayList<LatLng>> {
MapsActivity2 mContext;
PolylineOptions rectline;
public WebserviceTask(MapsActivity2 context) {
this.mContext = context;
}
#Override
protected void onPostExecute(ArrayList<LatLng> result) {
super.onPostExecute(result);
if (result != null) {
rectline = new PolylineOptions().width(10).color(Color.BLUE);
for (int i = 0; i < result.size(); i++)
rectline.add(result.get(i));
map.addPolyline(rectline);
}
}
#Override
protected ArrayList<LatLng> doInBackground(Void... params) {
GMapV2Direction md = new GMapV2Direction();
Document doc = md.getDocument(fromPosition, toPosition,
GMapV2Direction.MODE_DRIVING);
if (doc != null) {
ArrayList<LatLng> directionPoint = md.getDirection(doc);
rectline = new PolylineOptions().width(10).color(Color.RED);
for (int i = 0; i < directionPoint.size(); i++)
rectline.add(directionPoint.get(i));
return directionPoint;
} else
return null;
}
}
}
/**Implement the code Snipet in your initializeMap() Method***/
private void initializeMap()
{
if (map == null)
{
map = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
new WebserviceTask(this).execute();
map.moveCamera(CameraUpdateFactory.newLatLngZoom(fromPosition, 10));
map.addMarker(new MarkerOptions()
.title("Marker Location")
.snippet("Marker Location Address")
.position(fromPosition));
map.getUiSettings().setMapToolbarEnabled(true);
}
}
Related
now i am getting latitude and longitude n time, if i move with my phone the marker also moving according latitude and longitude, but i need to draw a route line if phone change the position. example i have T1, T2, T4, T5 time latitude longitude points i need to draw route line from T1 to T2 and T2 to T3 and T3 to T4 So on in real time, i am unable draw the lines.
MainActivity
public class MainActivity 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 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_main);
SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapFragment);
supportMapFragment.getMapAsync(this);
findViewById(R.id.currentLocationImageButton).setOnClickListener(clickListener);
mydb = new DatabaseHelper(this);
}
#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);
//locationRequest.setFastestInterval(1000);
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(MainActivity.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)));
addLines(latLng);
AddData(location);
}
#NonNull
private CameraPosition getCameraPositionWithBearing(LatLng latLng) {
addLines(latLng);
return new CameraPosition.Builder().target(latLng).zoom(16).build();
}
private void showMarker(#NonNull Location currentLocation) {
LatLng latLng = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
BitmapDescriptor icon =
BitmapDescriptorFactory.fromResource(R.drawable.ic_person_pin_circle_black_24dp);
addLines(latLng);
viewAll();
if (currentLocationMarker == null)
currentLocationMarker = googleMap.addMarker(new
MarkerOptions().icon(BitmapDescriptorFactory.defaultMarker()).flat(true).position(latLng));
else
MarkerAnimation.animateMarkerToGB(currentLocationMarker, latLng, new LatLngInterpolator.Spherical());
}
#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;
}
private void addLines(LatLng latLng) {
LatLng TIMES_SQUARE = new LatLng(latLng.latitude, latLng.longitude);
LatLng BROOKLYN_BRIDGE = new LatLng(latLng.latitude, latLng.longitude);
LatLng LOWER_MANHATTAN = new LatLng(latLng.latitude, latLng.longitude);
Log.i("===Lat", String.valueOf(latLng.latitude));
Log.i("===Longt", String.valueOf(latLng.longitude));
String polyLine = "q`epCakwfP_#EMvBEv#iSmBq#GeGg#}C]mBS{#KTiDRyCiBS";
List<LatLng> polyLineList = Collections.singletonList(TIMES_SQUARE);
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (LatLng latLng1 : polyLineList) {
builder.include(latLng1);
googleMap.addPolyline((new PolylineOptions())
//.add(TIMES_SQUARE, LOWER_MANHATTAN,TIMES_SQUARE).width(5).color(Color.RED)
//.add( new LatLng(14.2354843, 76.2484165), new LatLng(14.2251, 76.3980)).width(5).color(Color.RED)
.add(new LatLng(latLng.latitude, latLng.longitude), new LatLng(latLng.latitude, latLng.longitude)).addAll(polyLineList).width(5).color(Color.BLUE)
.geodesic(true));
PolylineOptions polylineOptions = new PolylineOptions();
polylineOptions.color(Color.BLACK);
polylineOptions.width(5);
polylineOptions.startCap(new SquareCap());
polylineOptions.endCap(new SquareCap());
polylineOptions.jointType(ROUND);
polylineOptions.addAll(polyLineList);
Polyline greyPolyLine = googleMap.addPolyline(polylineOptions);
}
;
// move camera to zoom on map
// googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(LOWER_MANHATTAN,13));
}
}
MarkerAnimation
public class MarkerAnimation {
public static void animateMarkerToGB(final Marker marker, final LatLng finalPosition, final LatLngInterpolator latLngInterpolator) {
final LatLng startPosition = marker.getPosition();
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
final Interpolator interpolator = new AccelerateDecelerateInterpolator();
final float durationInMs = 3000;
handler.post(new Runnable() {
long elapsed;
float t;
float v;
#Override
public void run() {
// Calculate progress using interpolator
elapsed = SystemClock.uptimeMillis() - start;
t = elapsed / durationInMs;
v = interpolator.getInterpolation(t);
marker.setPosition(latLngInterpolator.interpolate(v, startPosition, finalPosition));
// Repeat till progress is complete.
if (t < 1) {
// Post again 16ms later.
//handler.postDelayed(this, 16);
handler.postDelayed(this, 16);
}
}
});
}
}
LatLngInterpolator Interface
public interface LatLngInterpolator {
LatLng interpolate(float fraction, LatLng a, LatLng b);
class Spherical implements LatLngInterpolator {
/* From github.com/googlemaps/android-maps-utils */
#Override
public LatLng interpolate(float fraction, LatLng from, LatLng to) {
// http://en.wikipedia.org/wiki/Slerp
double fromLat = toRadians(from.latitude);
double fromLng = toRadians(from.longitude);
double toLat = toRadians(to.latitude);
double toLng = toRadians(to.longitude);
double cosFromLat = cos(fromLat);
double cosToLat = cos(toLat);
// Computes Spherical interpolation coefficients.
double angle = computeAngleBetween(fromLat, fromLng, toLat, toLng);
double sinAngle = sin(angle);
if (sinAngle < 1E-6) {
return from;
}
double a = sin((1 - fraction) * angle) / sinAngle;
double b = sin(fraction * angle) / sinAngle;
// Converts from polar to vector and interpolate.
double x = a * cosFromLat * cos(fromLng) + b * cosToLat * cos(toLng);
double y = a * cosFromLat * sin(fromLng) + b * cosToLat * sin(toLng);
double z = a * sin(fromLat) + b * sin(toLat);
// Converts interpolated vector back to polar.
double lat = atan2(z, sqrt(x * x + y * y));
double lng = atan2(y, x);
return new LatLng(toDegrees(lat), toDegrees(lng));
}
private double computeAngleBetween(double fromLat, double fromLng, double toLat, double toLng) {
// Haversine's formula
double dLat = fromLat - toLat;
double dLng = fromLng - toLng;
return 2 * asin(sqrt(pow(sin(dLat / 2), 2) +
cos(fromLat) * cos(toLat) * pow(sin(dLng / 2), 2)));
}
}
}
Consider replacing your addLines method with this which maintains and redraws polyline on every update:
private List<LatLng> polyLineList = new ArrayList<>();
private Polyline greyPolyLine;
private void addToLine(LatLng pt)
{
polyLineList.add(pt);
if (greyPolyLine != null)
{
greyPolyLine.remove();
}
PolylineOptions polylineOptions = new PolylineOptions();
polylineOptions.color(Color.BLACK);
polylineOptions.width(5);
polylineOptions.startCap(new SquareCap());
polylineOptions.endCap(new SquareCap());
polylineOptions.jointType(ROUND);
polylineOptions.addAll(polyLineList);
greyPolyLine = googleMap.addPolyline(polylineOptions);
}
You addLine was simply drawing a single point on every invocation - a single point is unlikely to be visible.
Probably only need to call it in the showMarker method - not sure why you're calling addLines in the camera methods.
I am new to android development currently trying to build car tracking app. Car marker is on the current location and it will move along with polyline as i move. I have implemented everything but polyline is not drawing behind marker need some suggestions where i am making mistake. Thank you in advance!
public class Map extends FragmentActivity implements OnMapReadyCallback,
GoogleMap.OnInfoWindowClickListener, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;
private static final int REQUEST_LOCATION = 0;
private Location mLastLocation;
// Google client to interact with Google API
private GoogleApiClient mGoogleApiClient;
// boolean flag to toggle periodic location updates
private boolean mRequestingLocationUpdates = false;
private LocationRequest mLocationRequest;
private static final String TAG = "";
private GoogleMap mMap;
private int markerCount;
TextView locationText;
String lat, longi, address1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map17);
locationText = (TextView) findViewById(R.id.locationText);
markerCount = 0;
//Check If Google Services Is Available
if (getServicesAvailable()) {
// Building the GoogleApi client
buildGoogleApiClient();
createLocationRequest();
Toast.makeText(this, "Google Service Is Available!!", Toast.LENGTH_SHORT).show();
}
//Create The MapView Fragment
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
startTrackerService();
}
private void startTrackerService() {
startService(new Intent(this, TrackerService.class));
}
/**
* GOOGLE MAPS AND MAPS OBJECTS
*/
// After Creating the Map Set Initial Location
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
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;
}
//Uncomment To Show Google Location Blue Pointer
// mMap.setMyLocationEnabled(true);
}
Marker mk = null;
// Add A Map Pointer To The MAp
public void addMarker(GoogleMap googleMap, double lat, double lon) {
if (markerCount == 1) {
animateMarker(mLastLocation, mk);
} else if (markerCount == 0) {
//Set Custom BitMap for Pointer
int height = 80;
int width = 45;
BitmapDrawable bitmapdraw = (BitmapDrawable) getResources().getDrawable(R.mipmap.icon_car);
Bitmap b = bitmapdraw.getBitmap();
Bitmap smallMarker = Bitmap.createScaledBitmap(b, width, height, false);
mMap = googleMap;
LatLng latlong = new LatLng(lat, lon);
mk = mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lon))
//.icon(BitmapDescriptorFactory.fromResource(R.drawable.pin3))
.icon(BitmapDescriptorFactory.fromBitmap((smallMarker))));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latlong, 16));
//Set Marker Count to 1 after first marker is created
markerCount = 1;
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
return;
}
//mMap.setMyLocationEnabled(true);
startLocationUpdates();
}
}
#Override
public void onInfoWindowClick(Marker marker) {
Toast.makeText(this, marker.getTitle(), Toast.LENGTH_LONG).show();
}
public boolean getServicesAvailable() {
GoogleApiAvailability api = GoogleApiAvailability.getInstance();
int isAvailable = api.isGooglePlayServicesAvailable(this);
if (isAvailable == ConnectionResult.SUCCESS) {
return true;
} else if (api.isUserResolvableError(isAvailable)) {
Dialog dialog = api.getErrorDialog(this, isAvailable, 0);
dialog.show();
} else {
Toast.makeText(this, "Cannot Connect To Play Services", Toast.LENGTH_SHORT).show();
}
return false;
}
/**
* LOCATION LISTENER EVENTS
*/
#Override
protected void onStart() {
super.onStart();
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
// startLocationUpdates();
}
#Override
protected void onResume() {
super.onResume();
getServicesAvailable();
// Resuming the periodic location updates
if (mGoogleApiClient.isConnected() && mRequestingLocationUpdates) {
startLocationUpdates();
}
}
#Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
#Override
protected void onPause() {
super.onPause();
}
//Method to display the location on UI
private void displayLocation() {
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
// Check Permissions Now
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_LOCATION);
} else {
mLastLocation = LocationServices.FusedLocationApi
.getLastLocation(mGoogleApiClient);
String location = String.valueOf(mLastLocation);
Log.d("lat:", location);
if (mLastLocation != null) {
double latitude = mLastLocation.getLatitude();
double longitude = mLastLocation.getLongitude();
String loc = "" + latitude + " ," + longitude + " ";
Toast.makeText(this, loc, Toast.LENGTH_SHORT).show();
Constants.lat1 = String.valueOf(latitude);
Constants.lat2 = String.valueOf(longitude);
Log.d("lat:", lat1);
Log.d("lat:", lat2);
//Add pointer to the map at location
addMarker(mMap, latitude, longitude);
try {
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(mLastLocation.getLatitude(), mLastLocation.getLongitude(), 1);
locationText.setText(locationText.getText() + "\n" + addresses.get(0).getAddressLine(0) + ", " +
addresses.get(0).getAddressLine(1) + ", " + addresses.get(0).getAddressLine(2));
address1 = String.valueOf(addresses.get(0).getAddressLine(0) + ", " +
addresses.get(0).getAddressLine(1) + ", " + addresses.get(0).getAddressLine(2));
Constants.address1 = address1;
Log.d("lat:", address1);
/* lat = String.valueOf(mLastLocation.getLatitude());
longi = String.valueOf(mLastLocation.getLongitude());
Log.d("lat:",lat);
Log.d("lat:","true1");
Log.d("longi:", longi);
Log.d("lat:","true2");
Constants.lattitude = lat;
Log.d("lat:",Constants.lattitude);
Log.d("lat:","true3");
Constants.longitude = longi;
Log.d("longi:", Constants.longitude);
Log.d("lat:","true4");
*/
} catch (Exception e) {
}
new ReplyAsync(getApplicationContext(), new ReplyAsync.getReplyAsyncCallback() {
#Override
public void onStart(boolean status) {
Log.e("Result true", "Result true................");
// progressDialog = new ProgressDialog(getApplicationContext());
// progressDialog.setTitle(Constants.company_name);
// progressDialog.setMessage(Constants.loadingMessage);
// progressDialog.show();
}
#Override
public void onResult(boolean result) {
if (result) {
Toast.makeText(Map.this, "Entered Successfully", Toast.LENGTH_SHORT).show();
Log.e("Result true", "Result true");
}
}
}).execute(Constants.latlonginsertlink);
} else {
Toast.makeText(this, "Couldn't get the location. Make sure location is enabled on the device",
Toast.LENGTH_SHORT).show();
}
}
}
// Creating google api client object
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
}
//Creating location request object
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(AppConstants.UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(AppConstants.FATEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setSmallestDisplacement(AppConstants.DISPLACEMENT);
}
//Starting the location updates
protected void startLocationUpdates() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission
(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// Check Permissions Now
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_LOCATION);
} else {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
}
//Stopping location updates
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
}
/**
* Google api callback methods
*/
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
+ result.getErrorCode());
}
#Override
public void onConnected(Bundle arg0) {
// Once connected with google api, get the location
displayLocation();
if (mRequestingLocationUpdates) {
startLocationUpdates();
}
}
#Override
public void onConnectionSuspended(int arg0) {
mGoogleApiClient.connect();
}
public void onLocationChanged(Location location) {
// Assign the new location
mLastLocation = location;
Toast.makeText(getApplicationContext(), "Location changed!",
Toast.LENGTH_SHORT).show();
// Displaying the new location on UI
displayLocation();
}
public static void animateMarker(final Location destination, final Marker marker) {
if (marker != null) {
final LatLng startPosition = marker.getPosition();
final LatLng endPosition = new LatLng(destination.getLatitude(), destination.getLongitude());
final float startRotation = marker.getRotation();
final LatLngInterpolator latLngInterpolator = new LatLngInterpolator.LinearFixed();
ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, 1);
valueAnimator.setDuration(1000); // duration 1 second
valueAnimator.setInterpolator(new LinearInterpolator());
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
try {
float v = animation.getAnimatedFraction();
LatLng newPosition = latLngInterpolator.interpolate(v, startPosition, endPosition);
marker.setPosition(newPosition);
marker.setRotation(computeRotation(v, startRotation, destination.getBearing()));
} catch (Exception ex) {
// I don't care atm..
}
}
});
valueAnimator.start();
}
}
private static float computeRotation(float fraction, float start, float end) {
float normalizeEnd = end - start; // rotate start to 0
float normalizedEndAbs = (normalizeEnd + 360) % 360;
float direction = (normalizedEndAbs > 180) ? -1 : 1; // -1 = anticlockwise, 1 = clockwise
float rotation;
if (direction > 0) {
rotation = normalizedEndAbs;
} else {
rotation = normalizedEndAbs - 360;
}
float result = fraction * rotation + start;
return (result + 360) % 360;
}
private interface LatLngInterpolator {
LatLng interpolate(float fraction, LatLng a, LatLng b);
class LinearFixed implements LatLngInterpolator {
#Override
public LatLng interpolate(float fraction, LatLng a, LatLng b) {
double lat = (b.latitude - a.latitude) * fraction + a.latitude;
double lngDelta = b.longitude - a.longitude;
// Take the shortest path across the 180th meridian.
if (Math.abs(lngDelta) > 180) {
lngDelta -= Math.signum(lngDelta) * 360;
}
double lng = lngDelta * fraction + a.longitude;
return new LatLng(lat, lng);
}
}
}
}
I am trying to use Geofire to store and display the users that are logged in on a map I am new in android studio as I am able to store location on firebase using geofire
but I am not able to retrieve the stored location from the firebase
Here is my code
public class tracking extends FragmentActivity implements
GeoQueryEventListener,OnMapReadyCallback,
GoogleMap.OnCameraChangeListener{
private static final GeoLocation INITIAL_CENTER = new GeoLocation(30.7333148, 76.7794179);
private static final int INITIAL_ZOOM_LEVEL = 14;
private static final String GEO_FIRE_DB = "https://trace-
5fa8c.firebaseio.com";
private static final String GEO_FIRE_REF = GEO_FIRE_DB + "/_geofire";
private GoogleMap mMap;
private GoogleMap map;
private Circle searchCircle;
private GeoFire geoFire;
private GeoQuery geoQuery;
private Map<String,Marker> markers;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tracking);
// Obtain the SupportMapFragment and get notified when the map is ready
to be used.
SupportMapFragment mapFragment = (SupportMapFragment)
getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync((OnMapReadyCallback) this);
// setup GeoFire
this.geoFire = new GeoFire(FirebaseDatabase.getInstance().getReferenceFromUrl(GEO_FIRE_REF));
// radius in km
this.geoQuery = this.geoFire.queryAtLocation(INITIAL_CENTER, 1);
// setup markers
this.markers = new HashMap<String, Marker>();
}
#Override
protected void onStop() {
super.onStop();
// remove all event listeners to stop updating in the background
this.geoQuery.removeAllListeners();
for (Marker marker: this.markers.values()) {
marker.remove();
}
this.markers.clear();
}
#Override
protected void onStart() {
super.onStart();
// add an event listener to start updating locations again
this.geoQuery.addGeoQueryEventListener(this);
}
#Override
public void onKeyEntered(String key, GeoLocation location) {
// Add a new marker to the map
Marker marker = this.map.addMarker(new MarkerOptions().position(new
LatLng(location.latitude, location.longitude)));
this.markers.put(key, marker);
}
#Override
public void onKeyExited(String key) {
// Remove any old marker
Marker marker = this.markers.get(key);
if (marker != null) {
marker.remove();
this.markers.remove(key);
}
}
#Override
public void onKeyMoved(String key, GeoLocation location) {
// Move the marker
Marker marker = this.markers.get(key);
if (marker != null) {
this.animateMarkerTo(marker, location.latitude, location.longitude);
}
}
#Override
public void onGeoQueryReady() {
}
#Override
public void onGeoQueryError(DatabaseError error) {
new AlertDialog.Builder(this)
.setTitle("Error")
.setMessage("There was an unexpected error querying GeoFire: " +
error.getMessage())
.setPositiveButton(android.R.string.ok, null)
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
// Animation handler for old APIs without animation support
private void animateMarkerTo(final Marker marker, final double lat, final
double lng) {
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
final long DURATION_MS = 3000;
final Interpolator interpolator = new
AccelerateDecelerateInterpolator();
final LatLng startPosition = marker.getPosition();
handler.post(new Runnable() {
#Override
public void run() {
float elapsed = SystemClock.uptimeMillis() - start;
float t = elapsed/DURATION_MS;
float v = interpolator.getInterpolation(t);
double currentLat = (lat - startPosition.latitude) * v +
startPosition.latitude;
double currentLng = (lng - startPosition.longitude) * v +
startPosition.longitude;
marker.setPosition(new LatLng(currentLat, currentLng));
// if animation is not finished yet, repeat
if (t < 1) {
handler.postDelayed(this, 16);
}
}
});
}
private double zoomLevelToRadius(double zoomLevel) {
// Approximation to fit circle into view
return 16384000/Math.pow(2, zoomLevel);
}
#Override
public void onCameraChange(CameraPosition cameraPosition) {
LatLng center = cameraPosition.target;
double radius = zoomLevelToRadius(cameraPosition.zoom);
this.searchCircle.setCenter(center);
this.searchCircle.setRadius(radius);
this.geoQuery.setCenter(new GeoLocation(center.latitude,
center.longitude));
// radius in km
this.geoQuery.setRadius(radius/1000);
}
#Override
public void onMapReady(GoogleMap googleMap) {
LatLng latLngCenter = new LatLng(INITIAL_CENTER.latitude,
INITIAL_CENTER.longitude);
this.searchCircle = this.map.addCircle(new
CircleOptions().center(latLngCenter).radius(1000));
this.searchCircle.setFillColor(Color.argb(66, 255, 0, 255));
this.searchCircle.setStrokeColor(Color.argb(66, 0, 0, 0));
this.map.moveCamera(CameraUpdateFactory.newLatLngZoom(latLngCenter,
INITIAL_ZOOM_LEVEL));
this.map.setOnCameraChangeListener(this);
}
}
I am not able to retrieve any location coordinates (log and lat)
please help
thanks in advance
I'm trying to make a simple location tracking app I tried many methods but nothing is working. I think onLocationChanged is not being called.
Here is my code :
#Override
public void onLocationChanged(Location location) {
Log.d("test", "onLocationChanged Called");
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
gMap.addMarker(new MarkerOptions().position(latLng));
gMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
gMap.animateCamera(CameraUpdateFactory.zoomTo(15));
Log.d("location", "Latitude:" + latitude + ", Longitude:" + longitude);
}
Here is my Whole code to run App. Just make new Project and Choose Map Project, Make your project on google console and Add the Key to your Project :
Add Permission to manifest :
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
Java Code :
package com.bluebirds.avinash.uberdemo;
import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Point;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.Projection;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements LocationListener,
OnMapReadyCallback, GoogleApiClient
.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private GoogleMap mMap;
private final int MY_LOCATION_REQUEST_CODE = 100;
private Handler handler;
private Marker m;
// private GoogleApiClient googleApiClient;
public final static int SENDING = 1;
public final static int CONNECTING = 2;
public final static int ERROR = 3;
public final static int SENT = 4;
public final static int SHUTDOWN = 5;
private static final String TAG = "LocationActivity";
private static final long INTERVAL = 1000 * 10;
private static final long FASTEST_INTERVAL = 1000 * 5;
Button btnFusedLocation;
TextView tvLocation;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mCurrentLocation;
String mLastUpdateTime;
private Location previousLocation;
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
createLocationRequest();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
// 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);
handler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case SENDING:
break;
}
}
};
}
/**
* 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);
m = mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in " +
"Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
} else {
// Show rationale and request permission.
}
}
public void rotateMarker(final Marker marker, final float toRotation, final float st) {
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
final float startRotation = st;
final long duration = 1555;
final Interpolator interpolator = new LinearInterpolator();
handler.post(new Runnable() {
#Override
public void run() {
long elapsed = SystemClock.uptimeMillis() - start;
float t = interpolator.getInterpolation((float) elapsed / duration);
float rot = t * toRotation + (1 - t) * startRotation;
marker.setRotation(-rot > 180 ? rot / 2 : rot);
if (t < 1.0) {
// Post again 16ms later.
handler.postDelayed(this, 16);
}
}
});
}
public void animateMarker(final LatLng toPosition, final boolean hideMarke) {
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
Projection proj = mMap.getProjection();
Point startPoint = proj.toScreenLocation(m.getPosition());
final LatLng startLatLng = proj.fromScreenLocation(startPoint);
final long duration = 5000;
final Interpolator interpolator = new LinearInterpolator();
handler.post(new Runnable() {
#Override
public void run() {
long elapsed = SystemClock.uptimeMillis() - start;
float t = interpolator.getInterpolation((float) elapsed
/ duration);
double lng = t * toPosition.longitude + (1 - t)
* startLatLng.longitude;
double lat = t * toPosition.latitude + (1 - t)
* startLatLng.latitude;
m.setPosition(new LatLng(lat, lng));
if (t < 1.0) {
// Post again 16ms later.
handler.postDelayed(this, 16);
} else {
if (hideMarke) {
m.setVisible(false);
} else {
m.setVisible(true);
}
}
}
});
}
private double bearingBetweenLocations(LatLng latLng1, LatLng latLng2) {
double PI = 3.14159;
double lat1 = latLng1.latitude * PI / 180;
double long1 = latLng1.longitude * PI / 180;
double lat2 = latLng2.latitude * PI / 180;
double long2 = latLng2.longitude * PI / 180;
double dLon = (long2 - long1);
double y = Math.sin(dLon) * Math.cos(lat2);
double x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1)
* Math.cos(lat2) * Math.cos(dLon);
double brng = Math.atan2(y, x);
brng = Math.toDegrees(brng);
brng = (brng + 360) % 360;
return brng;
}
/* #Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[]
grantResults) {
if (requestCode == MY_LOCATION_REQUEST_CODE) {
if (permissions.length == 1 &&
permissions[0] == Manifest.permission.ACCESS_FINE_LOCATION &&
grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
} else {
// Permission was denied. Display an error message.
}
}
}*/
#Override
public void onConnected(#Nullable Bundle bundle) {
Log.d(TAG, "onConnected - isConnected ...............: " + mGoogleApiClient.isConnected());
startLocationUpdates();
}
#Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart fired ..............");
mGoogleApiClient.connect();
}
#Override
protected void onStop() {
super.onStop();
mGoogleApiClient.disconnect();
Log.d(TAG, "isConnected ...............: " + mGoogleApiClient.isConnected());
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
protected void startLocationUpdates() {
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;
}
PendingResult<Status> pendingResult = LocationServices.FusedLocationApi
.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
Log.d(TAG, "Location update started ..............: ");
}
LatLng previouslatLng;
#Override
public void onLocationChanged(Location location) {
previouslatLng = new LatLng(location.getLatitude(), location.getLongitude());
double rota = 0.0;
double startrota = 0.0;
if (previousLocation != null) {
rota = bearingBetweenLocations(previouslatLng, new LatLng(location.getLatitude
(), location.getLongitude()));
}
rotateMarker(m, (float) rota, (float) startrota);
previousLocation = location;
Log.d(TAG, "Firing onLocationChanged..........................");
Log.d(TAG, "lat :" + location.getLatitude() + "long :" + location.getLongitude());
Log.d(TAG, "bearing :" + location.getBearing());
animateMarker(new LatLng(location.getLatitude(), location.getLongitude()), false);
// new ServerConnAsync(handler, MapsActivity.this,location).execute();
}
#Override
protected void onPause() {
super.onPause();
stopLocationUpdates();
}
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
Log.d(TAG, "Location update stopped .......................");
}
#Override
public void onResume() {
super.onResume();
if (mGoogleApiClient.isConnected()) {
startLocationUpdates();
Log.d(TAG, "Location update resumed .....................");
}
}
}
XML Activity :
<fragment android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.bluebirds.avinash.uberdemo.MapsActivity"/>
Use this code, you can track start location and end location, the marker moves from start location to end location,
1 . add Mainfest
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET"/>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="Your string" />
2 . In gradle
compile 'com.google.android.gms:play-services:7.0.0'
3 . Find activty,
public class FindActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
private GoogleMap mMap;
public Toolbar toolbar;
double latitude, logitude,prevLatitude,prevLongitude;
Button button;
GPSTracker3 gps;
String work="0";
TextView textView, t1, t2, t3;
Timer timer = new Timer();
private List<LatLng> bangaloreRoute;
ArrayList<LatLng> MarkerPoints;
Context mContext;
Button b1, b2;
CardView change;
List<LatLng> list;
Location location;
private static final CharSequence[] MAP_TYPE_ITEMS = {"Road Map", "Hybrid", "Satellite", "Terrain"};
Marker marker;
private Polyline line;
private ArrayList<LatLng> routePoints ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
list = new ArrayList<>();
SupportMapFragment mapFragment = (SupportMapFragment)
getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
mContext = this;
if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(FindActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
} else {
// Toast.makeText(mContext,"You need have granted permission",Toast.LENGTH_SHORT).show();
gps = new GPSTracker3(mContext, FindActivity.this);
// Check if GPS enabled
if (gps.canGetLocation()) {
latitude = gps.getLatitude();
logitude = gps.getLongitude();
// \n is for new line
// Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + lati + "\nLong: " + longi, Toast.LENGTH_LONG).show();
} else {
// Can't get location.
// GPS or network is not enabled.
// Ask user to enable GPS/network in settings.
// gps.showSettingsAlert();
}
}
if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 101);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
MarkerPoints = new ArrayList<>();
b1 = (Button) findViewById(R.id.start);
b2 = (Button) findViewById(R.id.end);
change = (CardView)findViewById(R.id.locate);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
work = "1";
b1.setVisibility(View.GONE);
b2.setVisibility(View.VISIBLE);
// bangaloreRoute.add(new LatLng(latitude, logitude));
// showMessageLocationUpdate();
}
});
if (bangaloreRoute == null) {
bangaloreRoute = new ArrayList<>();
} else {
bangaloreRoute.clear();
}
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// bangaloreRoute.clear();
list.clear();
work = "2";
b2.setVisibility(View.GONE);
b1.setVisibility(View.VISIBLE);
CaptureMapScreen();
}
});
change.setBackgroundResource(R.drawable.ic_sate);
change.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showMapTypeSelectorDialog();
}
});
}
public void CaptureMapScreen()
{
GoogleMap.SnapshotReadyCallback callback = new GoogleMap.SnapshotReadyCallback() {
Bitmap bitmap;
#Override
public void onSnapshotReady(Bitmap snapshot) {
// TODO Auto-generated method stub
bitmap = snapshot;
try {
FileOutputStream out = new FileOutputStream("/mnt/sdcard/"
+ "MyMapScreen" + System.currentTimeMillis()
+ ".png");
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
} catch (Exception e) {
e.printStackTrace();
}
}
};
mMap.snapshot(callback);
}
private void showMessageLocationUpdate() {
timer.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
StartCase(location);
}
});
}
}, 0, 100);
}
private void StartCase(Location location) {
if (work.equals("1")) {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);
list.add(latLng);
drawPolyLineOnMap(list);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(30));
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setZoomGesturesEnabled(true);
mMap.getUiSettings().setCompassEnabled(true);
mMap.getUiSettings().setZoomGesturesEnabled(true);
mMap.animateCamera(CameraUpdateFactory.zoomTo(17));
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
} else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
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) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_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) {
// getAddress(location.getLatitude(), location.getLongitude());
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// mMap.animateCamera(CameraUpdateFactory.zoomTo(17));
if (work.equals("1")) {
list.add(latLng);
drawPolyLineOnMap(list);
}
}
private void showMapTypeSelectorDialog(){
final String title = "Select Map Type";
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(title);
int checkCurrentMapType = mMap.getMapType() - 1;
builder.setSingleChoiceItems(MAP_TYPE_ITEMS,checkCurrentMapType,new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item){
switch(item){
case 1:
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
break;
case 2:
mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
break;
case 3:
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
break;
default:
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
dialog.dismiss();
}
});
//build dialog
AlertDialog fMapTypeDialogue = builder.create();
fMapTypeDialogue.setCanceledOnTouchOutside(true);
fMapTypeDialogue.show();
}
public void drawPolyLineOnMap(List<LatLng> list) {
PolylineOptions polyOptions = new PolylineOptions();
polyOptions.color(Color.RED);
polyOptions.width(3);
polyOptions.addAll(list);
mMap.clear();
mMap.addPolyline(polyOptions);
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (LatLng latLng : list) {
builder.include(latLng);
}
// final LatLngBounds bounds = builder.build();
//BOUND_PADDING is an int to specify padding of bound.. try 100.
// CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, 10);
// mMap.animateCamera(cu);
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public boolean checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
public void getAddress(double lat, double lng) {
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
Address obj = addresses.get(0);
String add = obj.getAddressLine(0);
String currentAddress = obj.getSubAdminArea() + ","
+ obj.getAdminArea();
double latitude = obj.getLatitude();
double longitude = obj.getLongitude();
String currentCity= obj.getSubAdminArea();
String currentState= obj.getAdminArea();
add = add + "\n" + obj.getCountryName();
add = add + "\n" + obj.getCountryCode();
add = add + "\n" + obj.getAdminArea();
add = add + "\n" + obj.getPostalCode();
add = add + "\n" + obj.getSubAdminArea();
add = add + "\n" + obj.getLocality();
add = add + "\n" + obj.getSubThoroughfare();
t1.setText(obj.getAdminArea());
t2.setText(obj.getSubAdminArea());
t3.setText(obj.getSubThoroughfare());
System.out.println("obj.getCountryName()"+obj.getCountryName());
System.out.println("obj.getCountryCode()"+obj.getCountryCode());
System.out.println("obj.getAdminArea()"+obj.getAdminArea());
System.out.println("obj.getPostalCode()"+obj.getPostalCode());
System.out.println("obj.getSubAdminArea()"+obj.getSubAdminArea());
System.out.println("obj.getLocality()"+obj.getLocality());
System.out.println("obj.getSubThoroughfare()"+obj.getSubThoroughfare());
Log.v("IGA", "Address" + add);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
Toast.makeText(this, "permission denied",
Toast.LENGTH_LONG).show();
}
return;
}
}
}
}
You can try https://github.com/balwinderSingh1989/androidBestLocationTracker
a simple to integrate lib with location algorithms that would get best location from GPS or network (whatever is avaiable)
Use this as reference project :- http://www.vogella.com/tutorials/AndroidLocationAPI/article.html
hi i have to implement Google map v2 in my application an it's perfect working. but my problem i have to send one Marker position from one activity to another activity and then add marker into Google map but i don't know it's not.
Post my code below.
public class BasicMapActivity extends FragmentActivity{
private GoogleMap mMap;
AlertMessages messages;
String latitude;
double lat = 0, lng = 0;
String longitude ;
String title = "", city = "";
static boolean is_back_pressed = false;
ImageView img;
GPSTracker gps;
RelativeLayout rel;
Marker Contactloc;
LatLng contactLoc;
Button ib_back;
static boolean is_window_pressed = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.basic_demo_new);
img = (ImageView) findViewById(R.id.popup_h);
img.setVisibility(View.INVISIBLE);
gps = new GPSTracker(getParent());
messages = new AlertMessages(getParent());
Bundle b = getIntent().getExtras();
title = b.getString("title");
city = b.getString("City");
latitude = b.getString("latitude");
longitude = b.getString("longitude");
back_layout=(LinearLayout)findViewById(R.id.back_lay);
ib_back=(Button)findViewById(R.id.ib_back_music);
System.out.println("Lat:::" + latitude);
System.out.println("Long:::" + longitude);
setUpMapIfNeeded();
ib_back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
is_back_pressed = true;
TabGroupActivity parentActivity = (TabGroupActivity) getParent();
parentActivity.onBackPressed();
}
});
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
try{
System.out.println("Map Pause state");
if(mMap!=null){
mMap.clear();
mMap=null;
TabGroupActivity parentActivity = (TabGroupActivity) getParent();
parentActivity.onBackPressed();
}
}catch(Exception e){
e.printStackTrace();
}
}
#Override
protected void onResume() {
super.onResume();
int status = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getParent());
if (status == ConnectionResult.SUCCESS) {
setUpMapIfNeeded();
mMap.setMyLocationEnabled(true);
} else {
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, getParent(),
requestCode);
dialog.show();
}
}
protected LocationManager locationManager;
LatLng pos=null;
private void setUpMapIfNeeded() {
System.out.println("Setup If Needed");
// Do a null check to confirm that we have not already instantiated the
// map.
if (mMap == null) {
mMap = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map1)).getMap();
mMap.setMyLocationEnabled(true);
boolean isInternetPresent = isConnectingToInternet();
if (!isInternetPresent) {
// Internet Connection is not present
Toast.makeText(getParent(), "Internet Connection Error!",Toast.LENGTH_SHORT).show();
//messages.showAlertDialog(getParent(),
// "Internet Connection Error",
//"Please connect to working Internet connection");
// stop executing code by return
// return;
} else {
locationManager = (LocationManager) getParent()
.getSystemService(LOCATION_SERVICE);
// getting GPS status
if (!locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
showSettingsAlert();
}
if (gps.canGetLocation()) {
lat = gps.getLatitude();
lng = gps.getLongitude();
pos = new LatLng(lat, lng);
if (lat == 0.0 && lng == 0.0) {
Toast.makeText(getParent(), "Can't find location",
Toast.LENGTH_SHORT).show();
} else {
mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.mark_blue))
.position(pos)
.title("Current Location"));
double trans = 0.3;
for (int k = 100; k <= 500;) {
// draw circle
int radiusM = k;
int d = k; // diameter
Bitmap bm = Bitmap.createBitmap(d, d,
Config.ARGB_8888);
Canvas c = new Canvas(bm);
Paint p = new Paint();
p.setColor(getResources().getColor(
android.R.color.darker_gray));
c.drawCircle(d / 2, d / 2, d / 2, p);
// generate BitmapDescriptor from circle
// Bitmap
BitmapDescriptor bmD = BitmapDescriptorFactory
.fromBitmap(bm);
// mapView is the GoogleMap
mMap.addGroundOverlay(new GroundOverlayOptions()
.image(bmD)
.position(pos, radiusM * 2,
radiusM * 2)
.transparency((float) trans));
k = k + 100;
trans = trans + 0.1;
}
}
} else {
Toast.makeText(getParent(), "Can't find location",
Toast.LENGTH_SHORT).show();
}
}
mMap.getUiSettings().setCompassEnabled(true);
mMap.setTrafficEnabled(true);
mMap.getUiSettings().setTiltGesturesEnabled(true);
mMap.getUiSettings().setRotateGesturesEnabled(true);
mMap.getUiSettings().setScrollGesturesEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setZoomGesturesEnabled(true);
setUpMap();
} // Check if we were successful in obtaining the map.
if (mMap != null) {
mMap.setMyLocationEnabled(true);
setUpMap();
}
}
private void setUpMap() {
System.out.println("Setup Map");
try{
contactLoc=new LatLng(latitude, longitude);
Contactloc=mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.mark_red))
.position(new LatLng(latitude, longitude)).title(title)
.snippet(city));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(
latitude, longitude), 18.0f));
}catch(Exception ew){
ew.printStackTrace();
}
}
}
please some one help me!
Add Marker like below
Contactloc=mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.mark_red))
.position(new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude)).title(title)
.snippet(city));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(
latitude, longitude), 18.0f));
You need to Convert your latitude and longitude String values into Double. and AFAIK you said no not any error. your app defiantly crash over here with some logcat.