My lastLocation show in few devices and cruch my app
Here is my code:
...............................................................................................................................................................................................................................................................
public class MapFragment extends Fragment implements OnMapReadyCallback {
private GoogleMap mGoogleMap;
private MapView mMapView;
private View mView;
private MarkerOptions marker;
private Location location;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.activity_maps, container, false);
return mView;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mMapView = view.findViewById(R.id.map);
if (mMapView != null) {
mMapView.onCreate(null);
mMapView.onResume();
mMapView.getMapAsync(this);
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
MapsInitializer.initialize(getContext());
mGoogleMap = googleMap;
addMarker();
googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
googleMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
location = locationManager.getLastKnownLocation(provider);
double lat = location.getLatitude();
double lng = location.getLongitude();
String lat1 = String.valueOf(lat);
String lng1 = String.valueOf(lng);
//Define list to get all latLng for the route
ArrayList<LatLng> path = new ArrayList<LatLng>();
//Execute Directions API request
GeoApiContext context = new GeoApiContext.Builder()
.apiKey(API_KEY)
.build();
DirectionsApiRequest req = DirectionsApi.getDirections(context, lat1 + ", " + lng1, "31.742462, 34.985447");
try {
DirectionsResult res = req.await();
//Loop through legs and steps to get encoded polyLines of each step
if (res.routes != null && res.routes.length > 0) {
DirectionsRoute route = res.routes[0];
if (route.legs != null) {
for (int i = 0; i < route.legs.length; i++) {
DirectionsLeg leg = route.legs[i];
if (leg.steps != null) {
for (int j = 0; j < leg.steps.length; j++) {
DirectionsStep step = leg.steps[j];
if (step.steps != null && step.steps.length > 0) {
for (int k = 0; k < step.steps.length; k++) {
DirectionsStep step1 = step.steps[k];
EncodedPolyline points1 = step1.polyline;
if (points1 != null) {
//Decode polyline and add points to list of route coordinates
List<com.google.maps.model.LatLng> coords1 = points1.decodePath();
for (com.google.maps.model.LatLng coord1 : coords1) {
path.add(new LatLng(coord1.lat, coord1.lng));
}
}
}
} else {
EncodedPolyline points = step.polyline;
if (points != null) {
//Decode polyline and add points to list of route coordinates
List<com.google.maps.model.LatLng> coords = points.decodePath();
for (com.google.maps.model.LatLng coord : coords) {
path.add(new LatLng(coord.lat, coord.lng));
}
}
}
}
}
}
}
}
} catch (Exception ignored) {
}
//Draw the polyline
if (path.size() > 0) {
PolylineOptions opts = new PolylineOptions().addAll(path).color(Color.BLUE).width(5);
googleMap.addPolyline(opts);
}
googleMap.getUiSettings().setZoomControlsEnabled(true);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(31.742462, 34.985447), 10));
}
public void addMarker() {
marker = new MarkerOptions().position(new LatLng(31.742462, 34.985447)).title("בית הכנסת - נווה צדק").icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));
mGoogleMap.addMarker(marker);
mGoogleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
Toast.makeText(getContext(), "בית הכנסת - נווה צדק", Toast.LENGTH_SHORT).show();
return true;
}
});
}
Related
How to show the location permission pop up with an allow and a deny button?
I have function that receives the location, but now I need to go to the settings by myself and turn the location on.
I want that when the User opens the fragment, the location pop up gets shown.
This is the code I currently have:
LocationFinder class:
public class LocationFinder extends Service implements LocationListener {
Context context;
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 200 * 10 * 1; // 2 seconds
// Declaring a Location Manager
protected LocationManager locationManager;
public LocationFinder(Context context) {
this.context = context;
getLocation();
}
#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) {
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#SuppressLint("MissingPermission")
public Location getLocation() {
try {
locationManager = (LocationManager) context
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
// Log.e("Network-GPS", "Disable");
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
// Log.e("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
} else
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
//Log.e("GPS Enabled", "GPS Enabled");
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 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() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("GPS settings");
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
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() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
}
Fragment that shows location:
public class GarageFragment extends Fragment {
LocationFinder finder;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_garage, container, false);
getLocation();
return view;
}
public void getLocation() {
double longitude = 0.0;
double latitude = 0.0;
finder = new LocationFinder(getContext());
if (finder.canGetLocation()) {
latitude = finder.getLatitude();
longitude = finder.getLongitude();
// Toast.makeText(getActivity(), "lat-lng " + latitude + "--" + longitude, Toast.LENGTH_LONG).show();
} else {
finder.showSettingsAlert();
}
Geocoder gcd = new Geocoder(getContext(), Locale.getDefault());
List<Address> addresses = null;
try {
addresses = gcd.getFromLocation(latitude, longitude, 1);
} catch (IOException e) {
e.printStackTrace();
}
if (addresses.size() > 0) {
Toast.makeText(getActivity(), addresses.get(0).getLocality(), Toast.LENGTH_LONG).show();
} else {
// do your stuff
}
}
}
add this code to check your permission
if (ContextCompat.checkSelfPermission(Activity.this, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ||
ContextCompat.checkSelfPermission(SplashActivity.this, ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
String[] PERMISSIONS = { ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION};
ActivityCompat.requestPermissions(Activity.this, PERMISSIONS, 600);
} else {
// your code
}
add in your resultActivity
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
Log.v("requestCode", "requestCode=" + requestCode);
switch (requestCode) {
case 600:
if (ActivityCompat.checkSelfPermission(this, permissions[0]) == PackageManager.PERMISSION_GRANTED
|| ActivityCompat.checkSelfPermission(this, permissions[1]) == PackageManager.PERMISSION_GRANTED) {
//allowed
} else {
//set to never ask again
ActivityCompat.requestPermissions(SplashActivity.this, new String[]{ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION}, 700);
}
break;
case 700:
if (ActivityCompat.checkSelfPermission(this, permissions[0]) == PackageManager.PERMISSION_GRANTED
|| ActivityCompat.checkSelfPermission(this, permissions[1]) == PackageManager.PERMISSION_GRANTED) {
//allowed
} else {
//set to never ask again
ActivityCompat.requestPermissions(SplashActivity.this, new String[]{ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION}, 700);
}
break;
}
}
Showing Location permission popup and turning location on are two different things.
You still have to go to setting to turn location on (if it's off), while permission is just allowing your app to use the location when it's on.
To get permission you can use this method RunTimePermissions.verifyStoragePermissions(getActivity());
public class RunTimePermissions {
// Storage Permissions variables
private static final int REQUEST_CODE = 6361;
private static String[] PERMISSIONS = {
Manifest.permission.ACCESS_FINE_LOCATION,
};
//persmission method.
public static void verifyStoragePermissions(Activity activity) {
// Check if we have read or write permission
int locationPermission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION);
if (locationPermission != PackageManager.PERMISSION_GRANTED ) {
// We don't have permission so prompt the user
ActivityCompat.requestPermissions(
activity,
PERMISSIONS,
REQUEST_CODE
);
}
}
}
Add in manifests:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Add in your activity:
public class MainActivity extends AppCompatActivity {
String[] locationPermissions= {"android.permission.ACCESS_COARSE_LOCATION","android.permission.ACCESS_FINE_LOCATION"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
if (ActivityCompat.checkSelfPermission(MainActivity.this,
android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(MainActivity.this,
android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(MainActivity.this, locationPermissions, 121);
}
}
};
handler.postDelayed(runnable, 1000);
}
}
I made an activity with google maps displayed, but I'd like to change it to Fragments, When I do that i get lots of errors.
I have problems with getMapAsync on the initmap method.
public class TAXIActivity extends Fragment implements OnMapReadyCallback {
private GoogleMap mMap;
private MapView mapView;
ArrayList LatitudeList = new ArrayList();
ArrayList LongitudeList = new ArrayList();
private FusedLocationProviderClient mFusedLocationProviderClient;
private Boolean mLocationPermissionsGranted = false;
private static final float DEFAULT_ZOOM = 15f;
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;
private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
private static final String COURSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_taxi, container, false);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_taxi);
/*
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
*/
getLocationPermission();
//someMethod();
}
public void onViewCreated (View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initMap();
}
#Override
public void onMapReady(GoogleMap googleMap) {
Toast.makeText(getContext(), "Map is Ready", Toast.LENGTH_SHORT).show();
Log.d("TAXIActivity", "onMapReady: map is ready");
mMap = googleMap;
someMethod();
if (mLocationPermissionsGranted) {
getDeviceLocation();
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(),
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
//mMap.getUiSettings().setMyLocationButtonEnabled(false);
}
//Log.d("TEST", "BBB");
//String LatMarkers = LatitudeList.toString();
//String LongMarkers = LongitudeList.toString();
//Log.d("TEST", "AAA");
/*
double latitude = Double.parseDouble(LatMarkers);
double longitude = Double.parseDouble(LongMarkers);
LatLng location = new LatLng(latitude, longitude);
//Log.d("TEST", "CCC");
mMap.addMarker(new MarkerOptions().position(location).title("Camera Location"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(location));
*/
//Log.d("TEST", "DDD");
}
OkHttpClient client = new OkHttpClient();
void someMethod() {
try {
String jsonData = new TAXIAPI(client).execute().get();
JSONObject object = new JSONObject(jsonData);
JSONArray RunningArray = object.getJSONArray("value");
for (int i = 0; i < RunningArray.length(); ++i) {
JSONObject objectInner = new JSONObject(RunningArray.getString(i));
String Latitude = objectInner.getString("Latitude");
String Longitude = objectInner.getString("Longitude");
double lat = Double.parseDouble(Latitude);
double lng = Double.parseDouble(Longitude);
LatLng location = new LatLng(lat, lng);
mMap.addMarker(new MarkerOptions().position(location).title("Taxi Location"));
//mMap.moveCamera(CameraUpdateFactory.newLatLng(location));//this will make camera focus on the last marker location
//LatitudeList.add(Latitude);
//LongitudeList.add(Longitude);
Log.d("APIActivity", " " + Latitude + " " + Longitude);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void getDeviceLocation() {
Log.d("TAXIActivity", "getDeviceLocation: getting the devices current location");
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getContext());
try {
if (mLocationPermissionsGranted) {
final Task location = mFusedLocationProviderClient.getLastLocation();
location.addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()) {
Log.d("TAXIActivity", "onComplete: found location!");
Location currentLocation = (Location) task.getResult();
moveCamera(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()),
DEFAULT_ZOOM);
} else {
Log.d("TAXIActivity", "onComplete: current location is null");
Toast.makeText(getContext(), "unable to get current location", Toast.LENGTH_SHORT).show();
}
}
});
}
} catch (SecurityException e) {
Log.e("TAXIActivity", "getDeviceLocation: SecurityException: " + e.getMessage());
}
}
private void moveCamera(LatLng latLng, float zoom) {
Log.d("TAXIActivity", "moveCamera: moving the camera to: lat: " + latLng.latitude + ", lng: " + latLng.longitude);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
}
private void initMap() {
Log.d("TAXIActivity", "initMap: initializing map");
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(TAXIActivity.this);
}
private void getLocationPermission() {
Log.d("TAXIActivity", "getLocationPermission: getting location permissions");
String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION};
if (ContextCompat.checkSelfPermission(getActivity().getApplicationContext(),
FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(getActivity().getApplicationContext(),
COURSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mLocationPermissionsGranted = true;
initMap();
} else {
ActivityCompat.requestPermissions(getActivity(),
permissions,
LOCATION_PERMISSION_REQUEST_CODE);
}
} else {
ActivityCompat.requestPermissions(getActivity(),
permissions,
LOCATION_PERMISSION_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
Log.d("TAXIActivity", "onRequestPermissionsResult: called.");
mLocationPermissionsGranted = false;
switch (requestCode) {
case LOCATION_PERMISSION_REQUEST_CODE: {
if (grantResults.length > 0) {
for (int i = 0; i < grantResults.length; i++) {
if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
mLocationPermissionsGranted = false;
Log.d("TAXIActivity", "onRequestPermissionsResult: permission failed");
return;
}
}
Log.d("TAXIActivity", "onRequestPermissionsResult: permission granted");
mLocationPermissionsGranted = true;
//initialize our map
initMap();
}
}
}
}
}
Error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.SupportMapFragment.getMapAsync(com.google.android.gms.maps.OnMapReadyCallback)' on a null object reference
at com.example.assignment1.TAXIActivity.initMap(TAXIActivity.java:199)
at com.example.assignment1.TAXIActivity.getLocationPermission(TAXIActivity.java:213)
at com.example.assignment1.TAXIActivity.onCreate(TAXIActivity.java:72)
You're getting google map fragment before your fragment view is created.
Right now you're doing, onCreate then getLocationPermission then initMap then .findFragmentById. Your google map fragment is not initialized at this point, that's why you're getting a null pointer exception when calling .getMapAsync.
Two solutions. Move you getLocationPermission to onViewCreated or remove initMap from getLocationPermission.
I'd do the second one, because Google Map doesn't need location permission.
I'm new creating apps and I want to show a drawn route in a Google Map starting from the current location. I've just found how to get the current location, but now I'm stuck in the second part, which is drawing the route from the current location to another marker point.
Here is my code:
`public class Trazo_Rutas extends FragmentActivity implements
OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private GoogleMap mMap;
GoogleApiClient googleApiClient;
LocationRequest locationRequest;
Location lastLocation;
Marker userLocation;
private static final int Request_User_Location_Code = 99;
PlaceAutocompleteFragment placeAutoComplete;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_trazo__rutas);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkUserLocationPermission();
}
//Check if Google Play Services Available or not
if (!CheckGooglePlayServices()) {
Log.d("onCreate", "Finishing test case since Google Play Services are not available");
finish();
}
else {
Log.d("onCreate","Google Play Services available.");
}
//AutoComplete search bar
placeAutoComplete = (PlaceAutocompleteFragment) getFragmentManager().findFragmentById(R.id.place_autocomplete);
placeAutoComplete.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
Log.d("Maps", "Place selected: " + place.getName());
}
#Override
public void onError(Status status) {
Log.d("Maps", "An error occurred: " + status);
}
});
// 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);
}
private boolean CheckGooglePlayServices() {
GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
int result = googleAPI.isGooglePlayServicesAvailable(this);
if(result != ConnectionResult.SUCCESS) {
if(googleAPI.isUserResolvableError(result)) {
googleAPI.getErrorDialog(this, result,
0).show();
}
return false;
}
return true;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.getUiSettings().setZoomControlsEnabled(true);
//get latlong for corners for specified place
LatLng corner1 = new LatLng(25.64379, -103.60966);
LatLng corner2 = new LatLng(25.64317, -103.20935);
LatLng corner3 = new LatLng(25.43872, -103.61104);
LatLng corner4 = new LatLng(25.43748, -103.20866);
LatLngBounds.Builder builder = new LatLngBounds.Builder();
builder.include(corner1);
builder.include(corner2);
builder.include(corner3);
builder.include(corner4);
LatLngBounds bounds = builder.build();
//add them to builder
int width = getResources().getDisplayMetrics().widthPixels;
int height = getResources().getDisplayMetrics().heightPixels;
// 20% padding
int padding = (int) (width * 0.20);
//set latlng bounds
mMap.setLatLngBoundsForCameraTarget(bounds);
//move camera to fill the bound to screen
mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, width, height, padding));
//set zoom to level to current so that you won't be able to zoom out viz. move outside bounds
mMap.setMinZoomPreference(mMap.getCameraPosition().zoom);
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);
}
}
public boolean checkUserLocationPermission() {
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
}, Request_User_Location_Code);
} else {
ActivityCompat.requestPermissions(this, new String[] {
Manifest.permission.ACCESS_FINE_LOCATION
}, Request_User_Location_Code);
}
return false;
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case Request_User_Location_Code:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
if (googleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
Toast.makeText(this, "Se requieren Permisos de Google", Toast.LENGTH_SHORT).show();
finish();
}
return;
}
}
protected synchronized void buildGoogleApiClient() {
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
googleApiClient.connect();
}
#Override
public void onLocationChanged(Location location) {
lastLocation = location;
if (userLocation != null) {
userLocation.remove();
}
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.draggable(true);
markerOptions.title("Tu ubicación");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
userLocation = mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 16));
if (googleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
locationRequest = new LocationRequest();
locationRequest.setInterval(1100);
locationRequest.setFastestInterval(1100);
locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
}`
My concern is that I don't know how to implement the other marker and draw the route.
Thank you.
I'm trying to get my location on click of save button & store that in
database.
Problem:
When I'm trying to get my location it shows me null pointer exception.
Can anyone tell me whats wrong in my code?
My code:
public class OthersFragment extends Fragment implements OnMapReadyCallback,GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
View view;
private GoogleMap mMap;
GoogleApiClient mGoogleApiClient;
Double latitude;
Double longitude;
String strplace;
public static OthersFragment newInstance() {
OthersFragment fragment = new OthersFragment();
return fragment;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// mGoogleApiClient = new GoogleApiClient.Builder(getContext())
// .addApi(LocationServices.API)
// .addConnectionCallbacks(this)
// .addOnConnectionFailedListener(this)
// .build();
view = inflater.inflate(R.layout.fragment_other, null, false);
SupportMapFragment mapFragment = (SupportMapFragment) this.getChildFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
return view;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleApiClient = new GoogleApiClient.Builder(getContext())
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() {
#Override
public boolean onMyLocationButtonClick() {
Location mylocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
ShowPopUp(mylocation);
return true;
}
});
googleMap.getUiSettings().setZoomControlsEnabled(true);
googleMap.getUiSettings().setAllGesturesEnabled(true);
}
private void ShowPopUp(final Location mylocation) {
int popupWidth = 300;
int popupHeight = 150;
// Inflate the popup_layout.xml
LinearLayout viewGroup = (LinearLayout)view.findViewById(R.id.popup);
LayoutInflater layoutInflater = (LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = layoutInflater.inflate(R.layout.popup, viewGroup);
// Creating the PopupWindow
final PopupWindow popup = new PopupWindow();
popup.setContentView(layout);
popup.setWidth(popupWidth);
popup.setHeight(popupHeight);
popup.setFocusable(true);
// Some offset to align the popup a bit to the right, and a bit down, relative to button's position.
int OFFSET_X = 30;
int OFFSET_Y = 30;
// Clear the default translucent background
popup.setBackgroundDrawable(new BitmapDrawable());
// Displaying the popup at the specified location, + offsets.
popup.showAtLocation(layout, Gravity.NO_GRAVITY, + OFFSET_X, OFFSET_Y);
// Getting a reference to Close button, and close the popup when clicked.
Button save = (Button) layout.findViewById(R.id.save);
Button retrieve = (Button) layout.findViewById(R.id.retrieve);
final EditText place = (EditText)layout.findViewById(R.id.place);
final EditText phone = (EditText)layout.findViewById(R.id.phone);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String action = "save";
String strplace = place.getText().toString();
String strphone = phone.getText().toString();
new storePoints().execute(strplace,String.valueOf(mylocation.getLatitude()), String.valueOf(mylocation.getLongitude()), action);
popup.dismiss();
}
});
retrieve.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String action = "retrieve";
strplace = place.getText().toString();
String strphone = phone.getText().toString();
new retrievePoints().execute(strplace, action);
popup.dismiss();
}
});
}
#Override
public void onConnected(Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
private class storePoints extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
try {
String place = (String) params[0];
// String phone = (String) params[1];
String latitude = (String) params[1];
String longitude = (String) params[2];
String action = (String) params[3];
String link = "http://192.168.0.152/prestige/saveCoord.php";
// String link = "http://10.0.2.2/coordinates/coord.php";
String data = URLEncoder.encode("station_name", "UTF-8") + "=" + URLEncoder.encode(place, "UTF-8");
// data += "&" + URLEncoder.encode("phone", "UTF-8") + "=" + URLEncoder.encode(phone, "UTF-8");
data += "&" + URLEncoder.encode("latitude", "UTF-8") + "=" + URLEncoder.encode(latitude, "UTF-8");
data += "&" + URLEncoder.encode("longitude", "UTF-8") + "=" + URLEncoder.encode(longitude, "UTF-8");
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while ((line = reader.readLine()) != null) {
sb.append(line);
break;
}
return sb.toString();
} catch (Exception e) {
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(OthersFragment.this.getContext(), result, Toast.LENGTH_LONG).show();
}
}
private class retrievePoints extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
try {
String place = (String) params[0];
String phone = (String) params[1];
String link = "http://192.168.0.152/prestige/retCoord.php";
// String link = "http://10.0.2.2/coordinates/retCoord.php";
String data = URLEncoder.encode("station_name", "UTF-8") + "=" + URLEncoder.encode(place, "UTF-8");
data += "&" + URLEncoder.encode("phone", "UTF-8") + "=" + URLEncoder.encode(phone, "UTF-8");
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while ((line = reader.readLine()) != null) {
sb.append(line);
break;
}
return sb.toString();
} catch (Exception e) {
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result) {
// Toast.makeText(MainActivity.this,result,Toast.LENGTH_LONG).show();
try {
mMap.clear(); // clear all the markers on the map.
JSONArray loc_arr = new JSONArray(result);
for (int i = 0; i < loc_arr.length(); i++){
JSONObject loc_obj = loc_arr.getJSONObject(i);
Double latitude = Double.valueOf((loc_obj.getString("latitude")));
Double longitude = Double.valueOf((loc_obj.getString("longitude")));
String place = loc_obj.getString("station_name");
// Toast.makeText(MainActivity.this, "latitude: "+latitude +"\t Longitude: " + longitude+"\t Place: "+place, Toast.LENGTH_SHORT).show();
Marker marker= mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("Place: "+place).snippet("Latitude: " +latitude+",Longitude: "+longitude));
marker.showInfoWindow();
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude,longitude),28));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Error Log:
06-20 12:30:42.740 6682-6682/com.example.barbegambino.apslocate E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.barbegambino.apslocate, PID: 6682
java.lang.NullPointerException
at com.example.barbegambino.apslocate.fragments.OthersFragment$2.onClick(OthersFragment.java:166)
at android.view.View.performClick(View.java:4463)
at android.view.View$PerformClick.run(View.java:18789)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5299)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:829)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:645)
at dalvik.system.NativeStart.main(Native Method)
For example try to get last-known location like below,
public class MapExample extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private GoogleMap mMap;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
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);
}
else{
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
// work with your last location.
} else {
Toast.makeText(this, R.string.no_location, Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
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);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission(){
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Asking user if explanation is needed
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted. Do the
// contacts-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
// Permission denied, Disable the functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
// other 'case' lines to check for other permissions this app might request.
// You can add here other case statements according to your requirement.
}
}
}
I added this and it worked for me.
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_entry, null, false);
//added
if (!isGooglePlayServicesAvailable()) {
Toast.makeText(getContext(), "Google Play Services is not available", Toast.LENGTH_LONG).show();
getActivity().finish();
}
mGoogleApiClient = new GoogleApiClient.Builder(getContext())
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
SupportMapFragment mapFragment = (SupportMapFragment) this.getChildFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
return view;
}
This also i added
#Override
public void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
public void onStop() {
super.onStop();
mGoogleApiClient.disconnect();
}
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getContext());
if (ConnectionResult.SUCCESS == status) {
return true;
} else {
GooglePlayServicesUtil.getErrorDialog(status, getActivity(), 0).show();
Toast.makeText(getContext(), "Google Play Services is not Available", Toast.LENGTH_LONG).show();
return false;
}
}
So I have looked around for examples of plotting routes on Google maps. However, my obstacle is that I have to go to url/route.coords in order to get the lat and lng for the route. When I go to that url manually it downloads a text file with all the route information. So if anyone could help me as to where to start that would be greatly appreciated. I already have the map showing along with a dot for your current location along with some other classes outlined. My end goal is to plot a different colored route for every drive, each drive has their specific URL.
Fragment for where I am showing my Google Maps:
public class ThirdFragment extends Fragment implements OnMapReadyCallback {
View myView;
private GoogleMap mMap;
MapFragment mapFrag;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.third_layout, container, false);
return myView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mapFrag = (MapFragment) getChildFragmentManager().findFragmentById(R.id.map);
mapFrag.getMapAsync(this);
//mapFrag.onResume();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
Criteria criteria = new Criteria();
LocationManager locationManager = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
String provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
double lat = location.getLatitude();
double lng = location.getLongitude();
LatLng coordinate = new LatLng(lat, lng);
CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(coordinate, 13);
mMap.animateCamera(yourLocation);
} else {
final AlertDialog alertDialogGPS = new AlertDialog.Builder(getActivity()).create();
alertDialogGPS.setTitle("Info");
alertDialogGPS.setMessage("Looks like you have not given GPS permissions. Please give GPS permissions and return back to the app.");
alertDialogGPS.setIcon(android.R.drawable.ic_dialog_alert);
alertDialogGPS.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intentSettings = new Intent(Settings.ACTION_APPLICATION_SETTINGS);
startActivity(intentSettings);
alertDialogGPS.dismiss();
}
});
alertDialogGPS.show();
}
}
#Override
public void onResume() {
super.onResume();
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mapFrag.getMapAsync(this);
}
else {
}
}
}
RouteCoord.java
public class RouteCoord {
private String lat, dist, lng, speed, index;
public String getLat() {
return lat;
}
public void setLat(String lat) {this.lat = lat;}
public String getLng(){return lng;}
public void setLng(String lng) {this.lng = lng;}
}
RouteAdapter.java
public class RouteAdapter extends ArrayAdapter<Map.Entry> {
private final Activity context;
// you may need to change List to something else (whatever is returned from drives.entrySet())
private final List<Map.Entry> drives;
public static String DriveURL;
public static String routeLat;
public static String routeLng;
SharedPreferences sharedPref;
// may also need to change List here (above comment)
public RouteAdapter(Activity context, List<Map.Entry> drives) {
super(context, R.layout.drive_url_list, drives);
this.context = context;
this.drives = drives;
sharedPref = context.getPreferences(Context.MODE_PRIVATE);
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.third_layout, null, true);
Map.Entry drive = this.drives.get(position);
// position is the index of the drives.entrySet() array
int driveNum = position + 1;
// need to import your Route class
Route route = (Route) drive.getValue();
RouteCoord routeCoord = (RouteCoord) drive.getValue();
routeLat = routeCoord.getLat();
routeLng = routeCoord.getLng();
// need to import your URL class
DriveURL = route.getUrl();
return rowView;
}
}
You need to draw a Polyline on the Google Map using the coordinates of the route.
See below sample code:
/**
* To show map with this activity add ORIGIN, DESTINATION lat double arrays in
* intent.
*
* </br> For specifying origin, put latitude and longitude in an array of double
* with key = {#link #ORIGIN} in the intent </br >For specifying destination,
* put latitude and longitude in an array of double with key =
* {#link #DESTINATION} in the intent
*
* #author Shridutt.Kothari
*
*/
public class MapsActivity extends BaseActivity {
private static final String TAG = "MapsActivity";
/**
* String key for specifying array of long containing origin latitude and
* longitude .
*/
public static final String ORIGIN = "ORIGIN";
private double[] destinationLocation;
private GoogleMap map;
private PathUpdateReceiver pathUpdateReceiver;
private PolylineOptions lineOptions;
private Marker marker;
private MarkerOptions ambulanceMarkerOption;
private Polyline polyline;
private List<LatLng> points;
private static final int ZOOM_LEVEL = 15;
private static final int POLYLINE_WIDTH = 5;
private static final String AMBULANCE_MARKER_NAME = "Ambulance";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
// Intent launchIntent = getIntent();
// originLocation = new double[2];
// originLocation = launchIntent.getDoubleArrayExtra(ORIGIN);
// originLocation[0] = 28.628525;
// originLocation[1] = 77.22219016666666;
destinationLocation = new double[2];
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
if (null == map) {
try {
MapsInitializer.initialize(getApplicationContext());
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"Google play services not available, can't show map!",
Toast.LENGTH_LONG).show();
e.printStackTrace();
this.finish();
}
}
}
#Override
protected void onResume() {
super.onResume();
if (null == pathUpdateReceiver) {
pathUpdateReceiver = new PathUpdateReceiver();
}
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(AppConstants.VEHICLE_DATA_SAMPLE_ID);
registerReceiver(pathUpdateReceiver, intentFilter);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(pathUpdateReceiver);
}
/**
* PathUpdate
*
*
*/
private class PathUpdateReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (map != null
&& intent.getAction().equalsIgnoreCase(
AppConstants.VEHICLE_DATA_SAMPLE_ID)) {
map.getUiSettings().setZoomControlsEnabled(true);
map.getUiSettings().setTiltGesturesEnabled(true);
map.getUiSettings().setAllGesturesEnabled(true);
VehicleDataSample vehicleDataSample = ((GoldenHourTrackerApp) getApplication()).getVehicleDataSample();
destinationLocation[0] = vehicleDataSample.getLatitude();
destinationLocation[1] = vehicleDataSample.getLongitude();
Log.e(TAG, "received location update:"+destinationLocation[0]+", "+destinationLocation[1]);
LatLng newPoint = new LatLng(destinationLocation[0],
destinationLocation[1]);
if (null != destinationLocation) {
map.setTrafficEnabled(false);
map.setBuildingsEnabled(true);
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
LatLng originlatlng = new LatLng(destinationLocation[0],
destinationLocation[1]);
map.moveCamera(CameraUpdateFactory.newLatLngZoom(
originlatlng, ZOOM_LEVEL));
-#SuppressWarnings("unused")
MarkerOptions traumaLoacationMarkerOption = new MarkerOptions()
.position(originlatlng)
.title(TRAUMA_LOCATION_MARKER_NAME)
.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_RED));
if (ambulanceMarkerOption == null) {
ambulanceMarkerOption = new MarkerOptions()
.position(originlatlng)
.title(AMBULANCE_MARKER_NAME)
.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
// TODO: Currently Not adding
// TRAUMA_LOCATION_MARKER_NAME on Map
// map.addMarker(traumaLoacationMarkerOption);
marker = map.addMarker(ambulanceMarkerOption);
marker.showInfoWindow();
}
if (null == lineOptions) {
lineOptions = new PolylineOptions();
lineOptions.add(newPoint);
// A 5 width Polyline
lineOptions.width(POLYLINE_WIDTH);
lineOptions.color(context.getResources().getColor(
R.color.blue));
polyline = map.addPolyline(lineOptions);
}
marker.setPosition(newPoint);
marker.setVisible(true);
marker.showInfoWindow();
map.animateCamera(CameraUpdateFactory.newLatLngZoom(
newPoint, ZOOM_LEVEL));
points = polyline.getPoints();
points.add(newPoint);
polyline.setPoints(points);
}
}
}
}
}