I recently started using Android Studio, and I'm just starting with the basics.
I tried to load in a google maps page, which is working fine. However, whenever I try to load in my location, i get a Null error:
java.lang.NullPointerException at com.example.wakelicious.MYPROJECTNAME.MapsActivity.setUpMap(MapsActivity.java:71)
Here is my MapsActivity:
package com.example.wakelicious.MYPROJECTNAME;
import com.example.wakelicious.MYPROJECTNAME.util.MyCurrentLocationListener;
import com.example.wakelicious.MYPROJECTNAME.util.SystemUiHider;
import android.content.Context;
import android.provider.SyncStateContract;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.view.Window;
import android.view.View;
import android.view.WindowManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.widget.TextView;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.LocationSource;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity {
private static final boolean AUTO_HIDE = true;
private static final int AUTO_HIDE_DELAY_MILLIS = 3000;
private static final boolean TOGGLE_ON_CLICK = true;
private static final int HIDER_FLAGS = SystemUiHider.FLAG_HIDE_NAVIGATION;
private SystemUiHider mSystemUiHider;
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
private TextView latituteField;
private TextView longitudeField;
private LocationManager locationManager;
private String provider;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (mMap == null) {
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_LOW);
provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
int lat = (int) (location.getLatitude());
latituteField = (TextView) findViewById(R.id.TextView02);
latituteField.setText(String.valueOf(lat));
mMap.setMyLocationEnabled(true);
CameraPosition myPosition = new CameraPosition.Builder()
.target(new LatLng(51.5736359, 5.0386894)).zoom(13).build();
mMap.animateCamera(
CameraUpdateFactory.newCameraPosition(myPosition));
mMap.addMarker(new MarkerOptions().icon(BitmapDescriptorFactory.fromResource(R.drawable.tilburg)).position(new LatLng(51.5736359, 5.0386894)).title("Tilburg"));
}
}
And in my Manifest i've added the following:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
I honestly don't know what is going wrong. I've turned on the GPS on my phone, and I even get a blue orb (my last known location, after i opened google maps) in the app with my location, but somehow I can't get the info from that location.
Does anyone know where I'm doing something wrong?
You're getting null because you're location has not been queried yet. As the method name implies, getLastKnownLocation, retrieves the last known location. Enabling GPS is not enough, you need to query for your location first.
What you want to do is to fetch the location if it's not yet present:
public class MainActivity extends Activity implements LocationListener {
private LocationManager mLocManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mLocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_LOW);
String provider = mLocManager.getBestProvider(criteria, true);
Location location = mLocManager.getLastKnownLocation(provider);
if (location == null) {
mLocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, );
} else {
setLat(location);
}
}
private void setLat(Location location) {
TextView latituteField = (TextView) findViewById(R.id.TextView02);
latituteField.setText(String.valueOf(location.getLatitude()));
}
#Override
public void onLocationChanged(Location location) {
if (location != null) {
setLat(location);
mLocManager.removeUpdates(this);
}
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {}
#Override
public void onProviderEnabled(String s) {}
#Override
public void onProviderDisabled(String s) {}
}
I too face the same problem. i have changed my criteria accuracy and my problem get solved.
criteria.setAccuracy(Criteria.ACCURACY_FINE);
or criteria.setAccuracy(Criteria.ACCURACY_HIGH);
Related
I am trying to create an app through a Youtube tutorial, but my app is getting crashed whenever I submit location in SearchView.
I have tried to change import android.support.v7.widget.SearchView; from import android.widget.SearchView;
import android.location.Geocoder;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v7.widget.SearchView;
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.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.io.IOException;
import java.util.List;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private SearchView searchView;
private SupportMapFragment mapFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
searchView = findViewById(R.id.location);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
String location = searchView.getQuery().toString();
List<Address> addressList = null;
if (location != null || location != "") {
Geocoder geocoder = new Geocoder(MapsActivity.this);
try {
addressList = geocoder.getFromLocationName(location, 1);
} catch (IOException e) {
e.printStackTrace();
}
Address address = addressList.get(0);
LatLng latLng = new LatLng(address.getLatitude(),address.getLongitude());
mMap.addMarker(new MarkerOptions().position(latLng).title(location));
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
}
return false;
}
#Override
public boolean onQueryTextChange(String query) {
return false;
}
});
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}
}```
"I expect that the app would not crash when I again hit enter to submit search in SearchView."
Change
if (location != null || location != "")
To
if (location != null || !location.equals(""))
We can't compare a string as I did before.
Add the stacktrace to the question to make it easier to identify the problem, but looking at the code if geocoder.getFromLocationName (location, 1) is null then Address address = addressList.get (0) will cause a NullPointerException
im writing android navigation app using geolocation but i have problem with frequency updating location.
picture
i get response in log.d() after approx 20 seconds. Im afraid its too slow for example when i use it while driving. The assumption is that the Marker should move smoothly.
NavigationActivity class:
package com.nowinski.kamil.drivertool;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.ui.PlaceAutocompleteFragment;
import com.google.android.gms.location.places.ui.PlaceSelectionListener;
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.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import java.io.IOException;
import java.util.List;
import java.util.zip.ZipEntry;
import utils.LatLngInterpolator;
import utils.MarkerAnimation;
public class NavigationActivity extends FragmentActivity implements
OnMapReadyCallback, LocationListener {
private GoogleMap mMap;
private LocationManager locationManager;
private Location location;
private double latitude;
private double longitude;
private PlaceAutocompleteFragment placeAutocompleteFragment;
private Marker marker;
private Marker markerCurrentLocation = null;
private final float ZOOM = 12.2f;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation);
// 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);
//initialize placeAutocompleteFragment and set on listener
placeAutocompleteFragment = (PlaceAutocompleteFragment) getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
placeAutocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
final LatLng latLngLoc = place.getLatLng();
if(marker!=null){
marker.remove();
}
marker = mMap.addMarker(new MarkerOptions().position(latLngLoc).title(place.getName().toString()));
mMap.animateCamera(CameraUpdateFactory.zoomTo(12), 2000, null);
}
#Override
public void onError(Status status) {
Toast.makeText(NavigationActivity.this, ""+status.toString(), Toast.LENGTH_SHORT).show();
}
});
//check permissions
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;
}
//initialize locationManager to get the location system service
locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, this);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location != null){
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}
private void updateMarkerPosition(Location newLocation){
//test
Log.d("locationChanged", Double.toString(newLocation.getLatitude())+" "+Double.toString(newLocation.getLongitude()));
LatLng newLatLng = new LatLng(newLocation.getLatitude(), newLocation.getLongitude());
//if marker used first time addMarker to map and move camera
if(markerCurrentLocation == null){
markerCurrentLocation = mMap.addMarker(new MarkerOptions().position(newLatLng));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(newLatLng, ZOOM));
} else {
MarkerAnimation.animateMarkerToICS(markerCurrentLocation, newLatLng, new LatLngInterpolator.Spherical());
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(newLatLng, ZOOM));
}
}
#Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
this.location = location;
updateMarkerPosition(location);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onProviderDisabled(String provider) {}
//activity life cycle
#Override
protected void onDestroy(){
super.onDestroy();
//stop GPS
locationManager.removeUpdates(this);
}
}
There are detected activities when user is walking or driving or running. Google doc.
But i suggest you implement this by using these well tested and maintained libraries like
1.https://github.com/akexorcist/Android-GoogleDirectionLibrary
2.https://github.com/jd-alexander/Google-Directions-Android
Which provide you many in library functions to use. and you will need not to RnD on everything of location listening.
I want to get back the position of my phone but I have a problem with this line:
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,10000,0,(LocationListener) this);
I know the problem is the permission check but I don't know to do this in my code:
package com.cmn.cmnvtc;
import android.app.Fragment;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MainPageFragment1 extends Fragment implements OnMapReadyCallback, LocationListener {
LocationManager locationManager;
public LatLng myLocation;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_main1, container, false);
locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,10000,0,(LocationListener) this);
return v;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
MapFragment fragment = (MapFragment) getChildFragmentManager().findFragmentById(R.id.map);
fragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
LatLng marker = new LatLng(48.9818555, 2.270541);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(marker, 15));
googleMap.addMarker(new MarkerOptions().title("Le garage").position(marker));
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
#Override
public void onLocationChanged(Location location) {
if(location != null){
Toast.makeText(getActivity(), "Latitude:" + location.getLatitude() + " - Longitude:" + location.getLongitude(), Toast.LENGTH_SHORT);
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
How can I do this , please?
My error is in the code : "Add permission check"
You need to check it for Marshmollow
private static final int GRANTED = PackageManager.PERMISSION_GRANTED;
if (checkCoarseLocationPermission(getActivity()) && checkFineLocationPermission(getActivity())) {
//permissions are granted
}else {
requestLocationPermission(getActivity());
}
}
public boolean checkCoarseLocationPermission(Activity mActivity){
int permissionCheck = ContextCompat.checkSelfPermission(mActivity,
Manifest.permission.ACCESS_COARSE_LOCATION);
return permissionCheck == GRANTED;
}
public boolean checkFineLocationPermission(Activity mActivity){
int permissionCheck = ContextCompat.checkSelfPermission(mActivity,
Manifest.permission.ACCESS_FINE_LOCATION);
return permissionCheck == GRANTED;
}
public void requestLocationPermission(Activity mActivity){
ActivityCompat.requestPermissions(mActivity,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
try this
public void onLocationChanged(Location location) {
if(location != null){
location = locationManager .getLastKnownLocation(LocationManager.GPS_PROVIDER);
Toast.makeText(getActivity(), "Latitude:" + location.getLatitude() + " - Longitude:" + location.getLongitude(), Toast.LENGTH_SHORT);
}
}
You need to add the permissions in the manifest of your app. Open your manifest.xml and put this two lines:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
ACCESS_FINE_LOCATION allows your app to track the user position using the actual GPS.
ACCESS_COARSE_LOCATION allows your app to track the user position using WiFi Networks, so you can omit this one if you are only using the GPS.
So I have searched the internet for lots of different solutions to get my android phone to show current location through the Google Maps API using play services. I believe I have the right set-up but something is just not right.
Please see below the .java and .xml code.
Java
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.location.LocationListener;
import android.os.Bundle;
import android.provider.SyncStateContract;
import android.support.v4.app.FragmentActivity;
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.SupportMapFragment;
import com.google.android.gms.maps.UiSettings;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private UiSettings mUiSettings;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
android.support.v4.app.FragmentManager myFragmentManager = getSupportFragmentManager();
SupportMapFragment mySupportMapFragment
= (SupportMapFragment) myFragmentManager.findFragmentById(R.id.map);
}
private void centerMapOnMyLocation() {
mMap.setMyLocationEnabled(true);
// Get LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Create a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Get the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
Location location = mMap.getMyLocation();
// Getting latitude
double latitude = location.getLatitude();
// Getting longitude
double longitude = location.getLongitude();
LatLng latlng;
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// public void requestPermissions(#NonNull String[] permissions, int requestCode)
// 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 Activity#requestPermissions for more details.
return;
}
Location myLocation = locationManager.getLastKnownLocation(provider);
if (location != null) {
//Create a LatLng object for the current location
latlng = new LatLng(latitude, longitude);
} else {
locationManager.requestLocationUpdates(provider, 20000, 0, (LocationListener) this);
}
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(location.getLatitude(), location.getLongitude())) // Sets the center of the map to location user
.zoom(17) // Sets the zoom
.bearing(90) // Sets the orientation of the camera to east
.tilt(40) // Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
}
XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:map="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/map"
tools:context="example.navigationapplication_10.MapsActivity"
android:name="com.google.android.gms.maps.SupportMapFragment"/>
</LinearLayout>
Many thanks
Try using this class to get the Latitude and Longitude..
import android.app.AlertDialog.Builder;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
public class GPSTracker extends Service implements LocationListener {
private Context context;
boolean isGPSEnabled=false;
boolean isNetworkEnabled=false;
boolean canGetLocation=false;
Location location;
double latitude;
double longitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES=10;
private static final long MIN_TIME_BW_UPDATES=1000*60*1;
protected LocationManager locationManager;
public GPSTracker(Context context)
{
this.context=context;
getLocation();
}
public Location getLocation()
{
try{
locationManager=(LocationManager) context.getSystemService(LOCATION_SERVICE);
isGPSEnabled=locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled=locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!isGPSEnabled && !isNetworkEnabled)
{
showSettingsAlert();
}
else{
this.canGetLocation=true;
if(isNetworkEnabled)
{
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if(locationManager !=null)
{
location=locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location !=null)
{
latitude=location.getLatitude();
longitude=location.getLongitude();
}
}
}
if(isGPSEnabled){
if(location==null)
{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if(locationManager !=null)
{
location=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location !=null)
{
latitude=location.getLatitude();
longitude=location.getLongitude();
}
}
}
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
return location;
}
public void stopUsingGPS()
{
if(locationManager !=null)
{
locationManager.removeUpdates(GPSTracker.this);
}
}
public double getLatitude()
{
if(location!=null)
{
latitude=location.getLatitude();
}
return latitude;
}
public double getLongitude()
{
if(location!=null)
{
longitude=location.getLongitude();
}
return longitude;
}
public boolean canGetLocation(){
return this.canGetLocation;
}
public void showSettingsAlert(){
Builder alertDialog=new Builder(context);
alertDialog.setTitle("GPS Settings");
alertDialog.setMessage("GPS is not enabled.Do you want to go to the settings menu?");
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent=new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
And for marking your position in the map
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
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.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
GPSTracker gps;
#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);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
try {
gps = new GPSTracker(MapsActivity.this);
if (gps.canGetLocation) {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
LatLng sydney = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(sydney).title("I am here"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
mMap.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
for(int i=0;i<MainActivity.nameArray.length;i++)
{
latitude=Double.parseDouble(MainActivity.latArray[i]);
longitude=Double.parseDouble(MainActivity.lonArray[i]);
LatLng shops = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(shops).title(MainActivity.nameArray[i]));
}
} else {
gps.showSettingsAlert();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Hope this Helps
this is my code of current location. i'm new to android so can anyone help me out ?
i need to send the current location to server and update it i certain time interval so that the user can fetch the location and display it on the map.it is basically a tracking device.
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MainActivity extends FragmentActivity implements LocationListener {
GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//show error dialog if GoolglePlayServices not available
if (!isGooglePlayServicesAvailable()) {
finish();
}
setContentView(R.layout.activity_main);
SupportMapFragment supportMapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.googleMap);
googleMap = supportMapFragment.getMap();
googleMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(bestProvider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(bestProvider, 20000, 0, this);
}
#Override
public void onLocationChanged(Location location) {
TextView locationTv = (TextView) findViewById(R.id.latlongLocation);
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
googleMap.addMarker(new MarkerOptions().position(latLng));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
locationTv.setText("Latitude:" + latitude + ", Longitude:" + longitude);
}
#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
}
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status) {
return true;
} else {
GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
return false;
}
}
}