Not showing marker on map - android

I want get the current location of user on map
when I run the app ,app is successfully launched it takes the permission from user to take location of user through GPS but marker is not showing on map.
when i run the this app on emulator it shows some where else location and when i run this app on mobile it does not show location(marker)
her is the code .
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
LocationManager locationManager;
LocationListener locationListener;
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode ==1) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Log.i("Location::::::", location.toString());
LatLng person = new LatLng(location.getLatitude(),location.getLongitude());
mMap.clear();
mMap.addMarker(new MarkerOptions().position(person).title("person").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE)));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(person, 15));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
if(Build.VERSION.SDK_INT < 23){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,0 ,locationListener);
}
else {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
} else {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
Location lastLoc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
LatLng loc = new LatLng(lastLoc.getLatitude(), lastLoc.getLongitude());
mMap.clear();
mMap.addMarker(new MarkerOptions().position(loc).title("person").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE)));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(loc, 15));
}
}
}
}

when i run the this app on emulator it shows some where else location
It's not showing your current location because when using the emulator, it's location is set in the settings, it doesn't determine your actual location, so basically it's set manually.
when i run this app on mobile it does not show location(marker)
Regarding that, you can try calling addMarker in onMapReady directly first. And moving your onLocationChanged callback outside of the onMapReady.

Related

I want my MainActivity.java to have a button which when tapped should execute the code written in MapsActivity.java

I created a MapsActivity and corresponding activity_maps.xml.My activity_main.xml there will be a button which when tapped should show the current location pointed by a marker.
Code works fine when making the MapsActivity as Launcher Activity in AndroidManifest.xml but want my MainActivity to be the Launcher Activity.
how I can make my MainActivity as Launcher Activity.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
LocationManager locationManager;
LocationListener locationListener;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
public void onMapReady(GoogleMap googleMap) {
Toast.makeText(this, "inside onMapReady()", Toast.LENGTH_SHORT).show();//doesn't appear
Log.i("hurray:","inside onMapReady()");//doesn't appear
mMap = googleMap;
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(#NonNull Location location) {
if(location != null){
Toast.makeText(MapsActivity.this, "Location is not null", Toast.LENGTH_SHORT).show();//doesn't appear
LatLng userLatLngLocation = new LatLng(location.getLatitude(),location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(userLatLngLocation);
markerOptions.title("Current position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));
mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(userLatLngLocation));
mMap.animateCamera(CameraUpdateFactory.zoomTo(10));
Toast.makeText(getApplicationContext(), location.toString(), Toast.LENGTH_SHORT).show();//does appears sometimes
}
else{
Toast.makeText(getApplicationContext(), "location is null !", Toast.LENGTH_SHORT).show();
}
}
public void requestLocationPermission() {
//if permission not granted ask for it
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
//else if location permission is already granted get location updates
else {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);//every 0secs & 0meters
}
}
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, int grantResults[]) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
}
}
}
MainActivity.java:
public class MainActivity extends AppCompatActivity {
Button getPopLocationButton;//button to show the Maps
MapsActivity mapsActivity;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_screen);
mapsActivity = new MapsActivity();
getPopLocationButton = findViewById(R.id.buttonPopLocation);
getPopLocationButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setContentView(R.layout.activity_maps);
}
});
}
}
Okay I got this working,
public void onClick(View view){
setContentView(R.layout.map);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(MainActivity.this);}

Google map with acceleration detection not working in android studio

I am making an app with Android Studio where the google maps shows the user's location, and i want to add an acceleration detector so when the acceleration of the user is very large, an alert dialog pops up.
The map with the user's location is working, but when I try to add the acceleration sensor, the app crashes (no error warning). The code is the following:
public abstract class Mapa extends FragmentActivity implements OnMapReadyCallback, SensorEventListener {
private GoogleMap mMap;
LocationManager locationManager;
LocationListener locationListener;
private SensorManager sensorManager;
Sensor accelerometer;
private SensorManager sensorManager2;
Sensor giroscopio;
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mapa);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION);
sensorManager.registerListener(Mapa.this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
#Override
public void onSensorChanged(SensorEvent sensorEvent) {
float acX;
acX = sensorEvent.values[0];
if (acX >= 10 ){
AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
builder1.setMessage("Warning!");
AlertDialog mensajealerta = builder1.create();
mensajealerta.show();
}
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
LatLng posicion = new LatLng(location.getLatitude(), location.getLongitude());
mMap.clear();
mMap.addMarker(new MarkerOptions().position(posicion).title("Estás aquí!"));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(posicion, 20));
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
if (Build.VERSION.SDK_INT < 23) {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
} else {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
} else { locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
Location ultimaPosicion = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
LatLng posicion = new LatLng(ultimaPosicion.getLatitude(), ultimaPosicion.getLongitude());
mMap.clear();
mMap.addMarker(new MarkerOptions().position(posicion).title("Estás aquí!"));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(posicion, 20));
}
}
}
}
I don't understand where the error is, could you help me please?
I finally figured it on my own, so I'll post the answer in case anyone else may need it.
Apparently it does not work when you put the Google maps and the accelerometer in the same activity, so I had to separate them. Ir order to do so, I used a Service for detecting the acceleration.
I managed to get my Service going by looking at this:
Android sensors not working in a service
Once this is done, I send my accelerometer info to my maps activity with a LocalBroadcastManager:
How to use LocalBroadcastManager?
By following the instructions given in these 2 questions I managed to make it work.

How to add a marker to the GoogleMap by clicking a button

I want to add a GoogleMap marker of my current position to the map(checkpoint) using a button. This is what I have so far. Probably one problem is that mMap is initialized inside onMapReady() function but how to go around it?
public class MainActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private FusedLocationProviderClient mFusedLocationProviderClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}
public void buttonClicked(View view) {
//Instantiate a Builder object
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
//Create an intent for the activity
Intent notifyIntent = new Intent(this, MainActivity.class);
//set the activity to start in a new, empty task
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
//Create pendingIntent
PendingIntent notifyPendingIntent = PendingIntent.getActivity(this, 0, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
//Put pendingIntent into the notification builder
builder.setContentIntent(notifyPendingIntent);
//Add components
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.common_google_signin_btn_icon_dark));
builder.setSmallIcon(R.drawable.common_google_signin_btn_icon_dark);
builder.setContentTitle("Content Title");
builder.setContentText("Content Text");
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1234, builder.build());
}
public void setStartLocation(View view) {
}
public void setWaypoint(View view) {
//place marker
//remove previous marker
//measure distance from starting position
//add to total milage
//time calculations too
}
public void setCheckpoint(View view) {
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mFusedLocationProviderClient.getLastLocation().addOnSuccessListener(this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if (location != null) {
LatLng position = new LatLng(location.getLatitude(), location.getLongitude());
mMap.addMarker(new MarkerOptions()
.position(position)
.title("Checkpoint"));
}
}
});
}
}
private GoogleMap mMap;
#Nullable
#Override
public View onCreateView() {
// code
startMap();
// code
}
private void startMap() {
// start map here
}
#Override
public void onMapReady(GoogleMap googleMap) {
// sometimes this function return null
if(googleMap == null) return;
mMap = googleMap;
}
and later:
public void setCheckpoint(View view) {
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mFusedLocationProviderClient.getLastLocation().addOnSuccessListener(this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if (location != null) {
LatLng position = new LatLng(location.getLatitude(), location.getLongitude());
if(mMap != null) {
mMap.addMarker(new MarkerOptions()
.position(position)
.title("Checkpoint"));
}
}
}
});
}

Android: Google maps not displaying in my app

I am following an online course to create an Uber clone. However, I am having an issue. From the emulator, when the rider option is clicked, I want to redirect to a new activity called "RiderActivity" and a map is supposed to be shown. However, nothing happens.
Here is my code for the new activity:
public class RiderActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
LocationManager locationManager;
LocationListener locationListener;
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode == 1){
if(grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
Location lastKnownLocation = locationManager.getLastKnownLocation(locationManager.GPS_PROVIDER);
updateMap(lastKnownLocation);
}
}
}
}
public void updateMap(Location location){
LatLng userLocation = new LatLng(location.getLatitude(),location.getLongitude());
mMap.clear();
mMap.moveCamera(CameraUpdateFactory.newLatLng(userLocation));
mMap.addMarker(new MarkerOptions().position(userLocation).title("Your Location"));
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rider);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//setup location manager and listerner
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE) ;
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
updateMap(location);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
if(Build.VERSION.SDK_INT < 23) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
} else{
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);
}else{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
Location lastKnownLocation = locationManager.getLastKnownLocation(locationManager.GPS_PROVIDER);
updateMap(lastKnownLocation);
}
}
// 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));
}
}
While in the MainActivity, I have a method
public void redirectActivity(){
if(ParseUser.getCurrentUser().get("riderOrDriver") == "rider"){
Intent intent = new Intent(getApplicationContext(),RiderActivity.class);
}
}
emulators do not support google maps, until just now, you need to download new emulators with play store support.
If you have done the above, you might wanna crosscheck your google map api key and check whether you have enabled maps api in developer api console.
Getting a map in app is rather a very simple step by step process as given in google map integration docs.

How to get the current location of the device? google maps

I need to know the latitude and longitude of the marker that is placed when I click on my map, and I also need to know how to implement so that when I open the map a marker is placed in the current location, I have seen many videos and tutorials but none works or It's obsolete etc
the relevant code:
onCreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
mPost = new Post();
initPantallaAdd();
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
if(status == ConnectionResult.SUCCESS){
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.mapAddUbicacion);
mapFragment.getMapAsync(this);
}else{
Toast.makeText(getApplicationContext(), "Please install google play services", Toast.LENGTH_SHORT).show();
}
}
onMapReady:
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
UiSettings uiSettings = mMap.getUiSettings();
uiSettings.setZoomControlsEnabled(true);
LatLng sydney = new LatLng(-0.193805, -78.467102);
CameraPosition cp = CameraPosition.builder().target(sydney).zoom(16).tilt(3).build();
float zoomlevel = 16;
mMap.moveCamera(CameraUpdateFactory.newCameraPosition(cp));
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
mMap.clear();
MarkerOptions markerOptions = new MarkerOptions().position(new LatLng(latLng.latitude, latLng.longitude)).title("Selected point");
mMap.addMarker(markerOptions);
}
});
}
I implemented these methods but I don't know what to do:
//==============================================================================================
// ON CONNECTION CALLBACKS
#Override
public void onConnected(#Nullable Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
//==============================================================================================
// LOCATION LISTENER
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
To work with map you have to follow some steps to configure it.
1- create a project at google developer console. https://console.developers.google.com/
2- select the project and leftmenu will show credential option click on it and than you will get option create credentialclick on it than it will ask for create api key click and create our project api key.
3-click on dashboard and select the project on top of the screen here you will get an option for enable api.
4- In this you will there is many google api, in the google map api section select google map api android and click enable .
now you will get a working api key this api key is used to work with map here i am giving you my repository you can take example from it. you do not need to configure for api key i am using my api key in it.
If you want to use you own api key than only you need to do is update the api key in the project inside manifiest file meta data tag. here is a working example
GPS service is needed to get current location latitude and longitude.
Android Location API will provide the fused location functionality to you. Check the following links for better understanding.
http://www.vogella.com/tutorials/AndroidLocationAPI/article.html
http://clover.studio/2016/08/09/getting-current-location-in-android-using-location-manager/
Check out this code for getting the current latitude and longitude...
public class MerchantTrack extends Common implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.merchant_track);
backbuttn=(ImageView)findViewById(R.id.backbuttn);
getSupportActionBar().hide();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
connectClient();
}
protected void connectClient() {
// Connect the client.
if (isGooglePlayServicesAvailable() && mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
}
private boolean isGooglePlayServicesAvailable() {
// Check that Google Play services is available
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
// If Google Play services is available
if (ConnectionResult.SUCCESS == resultCode) {
// In debug mode, log the status
Log.d("Location Updates", "Google Play services is available.");
return true;
} else {
// Get the error dialog from Google Play services
Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(resultCode, this,
CONNECTION_FAILURE_RESOLUTION_REQUEST);
// If Google Play services can provide an error dialog
if (errorDialog != null) {
// Create a new DialogFragment for the error dialog
UberMapsActivity.ErrorDialogFragment errorFragment = new UberMapsActivity.ErrorDialogFragment();
errorFragment.setDialog(errorDialog);
errorFragment.show(getSupportFragmentManager(), "Location Updates");
}
return false;
}
}
#Override
public void onConnected(Bundle bundle) {
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location != null) {
//Toast.makeText(this, "GPS location was found!", Toast.LENGTH_SHORT).show();
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
latitudE = location.getLatitude();
longitudE = location.getLongitude();
Log.d("locationnss", String.valueOf(latitudE));
new MerchLocAsync().execute();
} else {
new AlertDialog.Builder(MerchantTrack.this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage("Current location is unavailable!")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.show();
}
startLocationUpdates();
}
protected void startLocationUpdates() {
mLocationRequest = new LocationRequest();
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
mLocationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onBackPressed() {
Intent home = new Intent(MerchantTrack.this,Home.class);
startActivity(home);
super.onBackPressed();
}

Categories

Resources