I have successfully developed a program to update the marker as the user travels, however the text will only say "Current Location"
I would also like to populate the marker with Address information to the user when clicked. Below are some snippets of code emphasizing my intention, any help will be greatly appreciated! Thank you
Here is my current MapsActivity.java
import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Camera;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.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;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private GoogleMap mMap;
private GoogleApiClient client;
private LocationRequest locationRequest;
private Location lastLocation;
private Marker currentLocationMarker;
public static final int REQUEST_LOCATION_CODE = 99;
TextView textView;
Geocoder geocoder;
List<Address> addresses;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
checkLocationPermission();
}
// 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 onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch(requestCode)
{
case REQUEST_LOCATION_CODE:
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
//permission is granted
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
if(client == null){
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
}
else {
Toast.makeText(this, "Permission Denied!", Toast.LENGTH_LONG).show();
//Permission is denied
}
return;
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
Toast.makeText(this, "Click Icon in Top right for Current Location", Toast.LENGTH_LONG).show();
mMap = googleMap;
LatLng Phoenix = new LatLng(33.6056711, -112.4052378);
mMap.addMarker(new MarkerOptions().position(Phoenix).title("Default Location: Phoenix, AZ"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(Phoenix));
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient(){
client = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
client.connect();
}
#Override
public void onLocationChanged(Location location) {
lastLocation = location;
if(currentLocationMarker != null){
currentLocationMarker.remove();
}
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
textView = (TextView) findViewById(R.id.textView);
geocoder = new Geocoder(this, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
String address = addresses.get(0).getAddressLine(0);
String area = addresses.get(0).getLocality();
String city = addresses.get(0).getAdminArea();
String country = addresses.get(0).getCountryName();
String postalcode = addresses.get(0).getPostalCode();
String fullAddress = address+", "+area+", " +city+", " + country+ "," + postalcode;
textView.setText(fullAddress);
} catch (IOException e) {
e.printStackTrace();
}
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomBy(10));
if(client != null){
LocationServices.FusedLocationApi.removeLocationUpdates(client, this);
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
locationRequest = new LocationRequest();
locationRequest.setInterval(1000);
locationRequest.setFastestInterval(1000);
locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(client, locationRequest, this);
}
}
public boolean checkLocationPermission(){
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if(ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION))
{
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION_CODE);
}
else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION_CODE);
}
return false;
}
else
return true;
}
public void onZoom(View view) {
if (view.getId() == R.id.zoomIn) {
mMap.animateCamera(CameraUpdateFactory.zoomIn());
}
if (view.getId() == R.id.zoomOut) {
mMap.animateCamera(CameraUpdateFactory.zoomOut());
}
}
public void ChangeType(View view) {
if (mMap.getMapType() == GoogleMap.MAP_TYPE_NORMAL) {
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
Toast.makeText(this, "Satellite Map Style", Toast.LENGTH_LONG).show();
}
else if (mMap.getMapType() == GoogleMap.MAP_TYPE_SATELLITE) {
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
Toast.makeText(this, "Hybrid Map Style", Toast.LENGTH_LONG).show();
}
else if (mMap.getMapType() == GoogleMap.MAP_TYPE_HYBRID) {
mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
Toast.makeText(this, "Terrain Map Style", Toast.LENGTH_LONG).show();
}
else if (mMap.getMapType() == GoogleMap.MAP_TYPE_TERRAIN) {
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
Toast.makeText(this, "Normal Map Style", Toast.LENGTH_LONG).show();
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}
Here is the corresponding xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/img_header" >
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="40dp"
android:text="Test"
android:layout_centerHorizontal="true"
android:textSize="22sp"/>
</RelativeLayout>
StackTrace
05-17 09:15:49.411 15842-15842/edu.phoenix.mbl402.week3apptt2163 E/AndroidRuntime: FATAL EXCEPTION: main
Process: edu.phoenix.mbl402.week3apptt2163, PID: 15842
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.get(ArrayList.java:437)
at edu.phoenix.mbl402.week3apptt2163.MapsActivity.onLocationChanged(MapsActivity.java:139)
at com.google.android.gms.internal.location.zzay.notifyListener(Unknown Source:4)
at com.google.android.gms.common.api.internal.ListenerHolder.notifyListenerInternal(Unknown Source:8)
at com.google.android.gms.common.api.internal.ListenerHolder$zza.handleMessage(Unknown Source:16)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
FINAL EDIT:
#Override
public void onLocationChanged(Location location) {
lastLocation = location;
if(currentLocationMarker != null){
currentLocationMarker.remove();
}
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(getAddressForLatLng());
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
currentLocationMarker = mMap.addMarker((markerOptions));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
}
public static Address getAddressForLatLng(Context context, LatLng location) {
final int MAX_RESULTS = 1;
final Geocoder geocoder = new Geocoder(context, Locale.getDefault());
Address address = new Address(Locale.getDefault());
try {
final List<Address> addresses = geocoder.getFromLocation(location.latitude, location.longitude, MAX_RESULTS);
if (addresses != null && addresses.size() != 0) {
address = addresses.get(0);
}
return address;
} catch (IOException e) {
Log.e("Geocoding", "Geocoding was not possible");
}
return address;
}
You don't have to remove marker from map on each location update. reuse existing marker store reference to it.
Marker mMarker = mMap.addMarker(new MarkerOptions()......)
After creating mMarkerObject refresh its location in OnLocationChanged
mMarker.setTitle()
mMarker.setPosition(latLng);
If for some reason You still want to implement on click action
add interface to Your main activity OnMarkerClickListener and override OnMarkerClick and use showInfoWindow or something :)
EDIT: for geocrush try following ->
public static Address getAddressForLatLng(final Context context, final LatLng location) {
final int MAX_RESULTS = 1;
final Geocoder geocoder = new Geocoder(context, Locale.getDefault());
Address address = new Address(Locale.getDefault());
try {
final List<Address> addresses = geocoder.getFromLocation(location.latitude, location.longitude, MAX_RESULTS);
if (addresses != null && addresses.size() != 0) {
address = addresses.get(0);
}
return address;
} catch (IOException e) {
Log.e("Geocoding", "Geocoding was not possible");
}
return address;
}
Simplified more efficient version of onLocationChanged()
#Override
public void onLocationChanged(Location location) {
lastLocation = location;
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
currentLocationMarker.setPosition(latLng);
// make sure following setTitle gets String from getAddressForLatLng
currentLocationMarker.setTitle(getAddressForLatLng(latLng));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
}
You can use reverse geocoding to get a human-readable address string from your latitude and longitude.
Then use that address as the marker title, instead of "Current Location".
Specifically:
addresses = geocoder.getFromLocation(
location.getLatitude(),
location.getLongitude(),
// In this sample, get just a single address.
1);
address = adresses[0];
markerOptions.title(address);
(Error handling etc. left out, see link).
Related
I am Trying to Build an app where user can show their location and send an SMS to nearby hospital.
I am new to android studio and everything about it, but I quite made a progress with it.
I have 2 XML files, but I'll provide the JAVA CLASSES first
MapActivity.java
package maptesting.app;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
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.CircleOptions;
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 maptesting.app.databinding.ActivityMapBinding;
public class MapActivity<mapView> extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
private ActivityMapBinding binding;
private View mapView;
private GoogleMap mMap;
private GoogleApiClient client;
private LocationRequest locationRequest;
private Location lastlocation;
private LocationManager locationManager;
private Marker currentLocationmMarker;
public static final int REQUEST_LOCATION_CODE = 99;
int PROXIMITY_RADIUS = 15000;
double latitude, longitude;
private int LOCATION_MIN_DISTANCE = 20;
private int LOCATION_MIN_TIME = 4000;
private boolean requestingLocationUpdates;
//NEW
private int FINE_LOCATION_REQUEST_CODE = 10001;
private float Geofence_Radius = 4000;
private Object CircleOptions;
//NEW SMS
private LocationListener locationListener;
private final long mTime = 1000;
private final long mDist = 5;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMapBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
if (!isConnectedToNetwork()) {
Toast.makeText(this, "Turn on mobile data or Wifi", Toast.LENGTH_LONG).show();
finish();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapView = mapFragment.getView();
mapFragment.getMapAsync(this);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_LOCATION_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (client == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
Intent intent = getIntent();
finish();
startActivity(intent);
}
} else {
Toast.makeText(this, "Location Permission Denied", Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onMapReady(#NonNull GoogleMap googleMap) {
mMap = googleMap;
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
// View locationButton = ((View) mapView.findViewById(Integer.parseInt("1")).getParent()).findViewById(Integer.parseInt("2"));
//locationButton.callOnClick();
}
//NEW INPUT (SMS)
LatLng msgloc = new LatLng(lastlocation.getLatitude(), lastlocation.getLongitude());
locationListener = new LocationListener()
{
#Override
public void onLocationChanged(#NonNull Location location)
{
try
{
String phoneNum = "09553625915";
String loc = String.valueOf(msgloc);
String message = "Location = " + msgloc;
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNum, null, message, null, null);
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void onProviderEnabled(#NonNull String provider)
{
}
public void onProviderDisabled(#NonNull String provider)
{
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
};
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
try
{
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, mTime, mDist,
(android.location.LocationListener) locationListener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, mTime, mDist,
(android.location.LocationListener) locationListener);
}
catch (SecurityException e)
{
e.printStackTrace();
}
//END NEW INPUT (SMS)
}
private void buildGoogleApiClient() {
client = new GoogleApiClient.Builder(this).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
client.connect();
}
#Override
public void onLocationChanged(#NonNull Location location)
{
latitude = location.getLatitude();
longitude = location.getLongitude();
lastlocation = location;
if (currentLocationmMarker != null)
{
currentLocationmMarker.remove();
}
Log.d("lat = ", "" + latitude);
Log.d("lng = ", "" + longitude);
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Location");
AddCircle(latLng, Geofence_Radius);
//markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
//currentLocationmMarker = mMap.addMarker(markerOptions);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mMap.setMyLocationEnabled(true);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 12));
//mMap.animateCamera(CameraUpdateFactory.zoomBy(2));
//todo delete following lines
Object[] dataTransfer = new Object[2];
getNearbyPlacesData getNearbyPlacesData = new getNearbyPlacesData();
String url = getUrl(latitude, longitude, "hospital");
dataTransfer[0] = mMap;
dataTransfer[1] = url;
getNearbyPlacesData.execute(dataTransfer);
Toast.makeText(MapActivity.this, "Showing Nearby Hospitals", Toast.LENGTH_SHORT).show();
//todo end
if (client != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(client, this);
}
}
private String getUrl(double latitude, double longitude, String nearbyPlace)
{
StringBuilder googlePlaceUrl = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
googlePlaceUrl.append("location=" + latitude + "," + longitude);
googlePlaceUrl.append("&radius=" + PROXIMITY_RADIUS);
googlePlaceUrl.append("&type=" + nearbyPlace);
googlePlaceUrl.append("&sensor=true");
//Todo: add your google api key here
googlePlaceUrl.append("&key=" + "YOUR_API_KEY");
Log.d("MapsActivity", "url = " + googlePlaceUrl.toString());
return googlePlaceUrl.toString();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
locationRequest = new LocationRequest();
locationRequest.setInterval(5);
locationRequest.setFastestInterval(500);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// ORG
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(client, locationRequest, this);
}
}
private boolean checkLocationPermission()
{
if(ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED )
{
if (ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.ACCESS_FINE_LOCATION))
{
ActivityCompat.requestPermissions(this,new String[] {Manifest.permission.ACCESS_FINE_LOCATION },REQUEST_LOCATION_CODE);
}
else
{
ActivityCompat.requestPermissions(this,new String[] {Manifest.permission.ACCESS_FINE_LOCATION },REQUEST_LOCATION_CODE);
}
return false;
}
else
{
return true;
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
private boolean isConnectedToNetwork() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED;
}
// Add Circle
private void AddCircle(LatLng latLng, float radius)
{
mMap.addCircle(new CircleOptions()
.center(latLng)
.radius(Geofence_Radius)
.strokeColor(Color.argb(50, 0, 0, 0))
.fillColor(Color.argb(13,0,0,0))
.strokeWidth(4));
}
What I want to see if its possible to send the user's current location to another phone after I hit the button that will also show their current location in the map.
I am willing to provide the source code if you kind sirs and ma'ams want to check my code.
Thank you
I'm new to android app dev and Java isn't my strongest programming language.
I able to make my user to allow their location to be access or deny to get their location longitude and latitude number. Though, I still can't figure our how to implement the precision changes of the location to either increase or decrease their coordinate number. I read all the documentation for android in this topic and still don't understand it.
Here's the code:
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import com.google.android.material.snackbar.Snackbar;
public class Locator extends AppCompatActivity {
Button back;
private final String enable = "Enable yout location for the GPS to work";
private final String loading = "GPS is starting";
private final String latAndLong = "Latitude: %s\n Longitude: %s\n";
private LocationManager lm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.location);
back = findViewById(R.id.backbutton);
back.setOnClickListener(view -> {
Intent intent = new Intent(Locator.this, MainActivity.class);
startActivity(intent);
});
}
public void getLocation(View v) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, getResources().getInteger(R.integer.requestCode));
lm = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean isProviderEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!isProviderEnabled) {
Snackbar.make(v, enable, Snackbar.LENGTH_LONG).setAction("Action",
null).show();
} else {
userLoca();
}
}
private void userLoca() {
TextView tvLocation = findViewById(R.id.textView_locator);
if (ActivityCompat.checkSelfPermission(Locator.this,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
tvLocation.setText(getResources().getString(R.string.location_denied));
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, getResources().getInteger(R.integer.requestCode));
} else if (ActivityCompat.checkSelfPermission(Locator.this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
tvLocation.setText(getResources().getString(R.string.location_denied));
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, getResources().getInteger(R.integer.requestCode));
} else {
tvLocation = findViewById(R.id.textView_locator);
Location current_GPS = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Location networkLocation = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Location passiveLocation = lm.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
if (current_GPS != null) {
tvLocation.setText(String.format(latAndLong, current_GPS.getLatitude(),
current_GPS.getLongitude()));
}
if (networkLocation != null) {
tvLocation.setText(String.format(latAndLong, networkLocation.getLatitude(),
networkLocation.getLongitude()));
}
if (passiveLocation != null) {
tvLocation.setText(String.format(latAndLong, passiveLocation.getLatitude(),
passiveLocation.getLongitude()));
} else {
Snackbar.make(tvLocation, loading, Snackbar.LENGTH_LONG).setAction("Action",
null).show();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,
getResources().getInteger(R.integer.location_min_time),
getResources().getInteger(R.integer.location_min_dist), v -> {
});
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
getResources().getInteger(R.integer.location_min_time),
getResources().getInteger(R.integer.location_min_dist), v -> {
});
}
}
}
}
You need to implement location updates listener to this. Use the following code:
private LocationCallback locationCallback;
Call this in onCreate() or onResume() depending upon your logic
locationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult == null) {
return;
}
for (Location location : locationResult.getLocations()) {
// Update UI with location data
// ...
}
}
};
private void startLocationUpdates() {
fusedLocationClient.requestLocationUpdates(locationRequest,
locationCallback,
Looper.getMainLooper());
}
I'm pretty new to android development and I'm unable to get the current location of gps and display the array of markers on the maps.
Also i'm trying to draw a path with distance and time calculation by following this tutorial in this link: https://javapapers.com/android/draw-path-on-google-maps-android-api/
and how would I send the values of the gps coordinates, distance and duration with a unique id to a firebase realtime database
Where am I going wrong?
import androidx.fragment.app.FragmentActivity;
import android.annotation.SuppressLint;
import android.os.Bundle;
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.lang.reflect.Array;
import java.util.ArrayList;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private Location currentLocation;
private FusedLocationProviderClient fusedLocationProviderClient;
private static final int LOCATION_REQUEST_CODE =101;
ArrayList<LatLng>arrayList=new ArrayList<LatLng>();
LatLng route1 = new LatLng(-35.016, 143.321);
LatLng route2 = new LatLng(-34.747, 145.592);
LatLng route3 = new LatLng(-34.364, 147.891);
LatLng route4 = new LatLng(-33.501, 150.217);
LatLng route5 = new LatLng(-32.306, 149.248);
LatLng route6 = new LatLng(-32.491, 147.309);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
arrayList.add(route1);
arrayList.add(route2);
arrayList.add(route3);
arrayList.add(route4);
arrayList.add(route5);
arrayList.add(route6);
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
if (ActivityCompat.checkSelfPermission(MapsActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MapsActivity.this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[] {android.Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_REQUEST_CODE);
return;
}
fetchLastLocation();
}
private void fetchLastLocation(){
Task<Location> task = fusedLocationProviderClient.getLastLocation();
task.addOnSuccessListener(new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if (location != null) {
currentLocation = location;
Toast.makeText(MapsActivity.this,currentLocation.getLatitude()+" "+currentLocation.getLongitude(),Toast.LENGTH_SHORT).show();
SupportMapFragment supportMapFragment= (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
supportMapFragment.getMapAsync(MapsActivity.this);
}else{
Toast.makeText(MapsActivity.this,"No Location recorded",Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
for (int i = 0; i < arrayList.size(); i++) {
mMap.addMarker(new MarkerOptions().position(arrayList.get(i)).title("Marker"));
LatLng latLng = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
//MarkerOptions are used to create a new Marker.You can specify location, title etc with MarkerOptions
MarkerOptions markerOptions = new MarkerOptions().position(latLng).title("You are Here");
googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
//Adding the created the marker on the map
googleMap.addMarker(markerOptions);
}
#SuppressLint("NeedOnRequestPermissionsResult")
#Override
public void onRequestPermissionsResult ( int requestCode, String[] permissions,int[] grantResult){
switch (requestCode) {
case LOCATION_REQUEST_CODE:
if (grantResult.length > 0 && grantResult[0] == PackageManager.PERMISSION_GRANTED) {
fetchLastLocation();
} else {
Toast.makeText(MapsActivity.this, "Location permission missing", Toast.LENGTH_SHORT).show();
}
break;
}
}
}
}
You have defined twice SupportMapFragment please check my code is working fine I have run code and solved the error
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.FragmentActivity;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import java.util.ArrayList;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private Location currentLocation;
private FusedLocationProviderClient fusedLocationProviderClient;
private static final int LOCATION_REQUEST_CODE = 101;
ArrayList arrayList = new ArrayList();
LatLng route1 = new LatLng(-35.016, 143.321);
LatLng route2 = new LatLng(-34.747, 145.592);
LatLng route3 = new LatLng(-34.364, 147.891);
LatLng route4 = new LatLng(-33.501, 150.217);
LatLng route5 = new LatLng(-32.306, 149.248);
LatLng route6 = new LatLng(-32.491, 147.309);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
arrayList.add(route1);
arrayList.add(route2);
arrayList.add(route3);
arrayList.add(route4);
arrayList.add(route5);
arrayList.add(route6);
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
if (ActivityCompat.checkSelfPermission(MapsActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MapsActivity.this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_REQUEST_CODE);
return;
}
fetchLastLocation();
}
private void fetchLastLocation() {
Task<Location> task = fusedLocationProviderClient.getLastLocation();
task.addOnSuccessListener(new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if (location != null) {
currentLocation = location;
Toast.makeText(MapsActivity.this, currentLocation.getLatitude() + " " + currentLocation.getLongitude(), Toast.LENGTH_SHORT).show();
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(MapsActivity.this);
} else {
Toast.makeText(MapsActivity.this, "No Location recorded", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
#Override
public void onMapLoaded() {
for (int i = 0; i < arrayList.size(); i++) {
mMap.addMarker(new MarkerOptions().position((LatLng) arrayList.get(i)).title("Marker"));
LatLng latLng = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
//MarkerOptions are used to create a new Marker.You can specify location, title etc with MarkerOptions
MarkerOptions markerOptions = new MarkerOptions().position(latLng).title("You are Here");
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,16));
//Adding the created the marker on the map
googleMap.addMarker(markerOptions);
}
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResult) {
switch (requestCode) {
case LOCATION_REQUEST_CODE:
if (grantResult.length > 0 && grantResult[0] == PackageManager.PERMISSION_GRANTED) {
fetchLastLocation();
} else {
Toast.makeText(MapsActivity.this, "Location permission missing", Toast.LENGTH_SHORT).show();
}
break;
}
}
}
My code is searching for nearby restaurants and working well by showing all nearest restaurants on Map,
But i want to get very near restaurant, i want to show only 1 restaurant in TextView, i don't know how i can calculate shortest path for that. Please help, Thanks:)
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.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.util.HashMap;
import java.util.List;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private GoogleMap mMap;
double latitude;
double longitude;
private int PROXIMITY_RADIUS = 10000;
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();
}
//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.");
}
// 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;
}
/**
* 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_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);
}
Button btnRestaurant = (Button) findViewById(R.id.btnRestaurant);
btnRestaurant.setOnClickListener(new View.OnClickListener() {
String Restaurant = "restaurant";
#Override
public void onClick(View v) {
Log.d("onClick", "Button is Clicked");
mMap.clear();
String url = getUrl(latitude, longitude, Restaurant);
Object[] DataTransfer = new Object[2];
DataTransfer[0] = mMap;
DataTransfer[1] = url;
Log.d("onClick", url);
GetNearbyPlacesData getNearbyPlacesData = new GetNearbyPlacesData();
getNearbyPlacesData.execute(DataTransfer);
Toast.makeText(MapsActivity.this,"Nearby Restaurants", Toast.LENGTH_LONG).show();
}
});
}
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);
}
}
private String getUrl(double latitude, double longitude, String nearbyPlace) {
StringBuilder googlePlacesUrl = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
googlePlacesUrl.append("location=" + latitude + "," + longitude);
googlePlacesUrl.append("&radius=" + PROXIMITY_RADIUS);
googlePlacesUrl.append("&type=" + nearbyPlace);
googlePlacesUrl.append("&sensor=true");
googlePlacesUrl.append("&key=" + "AIzaSyATuUiZUkEc_UgHuqsBJa1oqaODI-3mLs0");
Log.d("getUrl", googlePlacesUrl.toString());
return (googlePlacesUrl.toString());
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
Log.d("onLocationChanged", "entered");
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
latitude = location.getLatitude();
longitude = location.getLongitude();
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));
Toast.makeText(MapsActivity.this,"Your Current Location", Toast.LENGTH_LONG).show();
Log.d("onLocationChanged", String.format("latitude:%.3f longitude:%.3f",latitude,longitude));
//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
Log.d("onLocationChanged", "Removing Location Updates");
}
Log.d("onLocationChanged", "Exit");
}
#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.
}
}
}
Pseudocode for finding the item that is closest:
closest = none;
for each item in items
{
if(!closest || item.distance > closest.distance)
{
closest = item
}
}
print "Closest Item is: " closest
you can use the latest google api
http://developer.android.com/google/play-services/maps.html
You can take a look at following link to draw path
Drawing a line/path on Google Maps
How to Draw Route in Google Maps API V2 from my location
Android: How to draw route directions google maps API V2 from current location to destination
I am using google maps on my app. I have an ArrayList where has lat, long and other information. I want to make click on a marker and go to other Activity with specific marker info to show details.
I have used this code but always get the last position of ArrayList. How to get each position's information?
package com.teledaktar.activities.mapsAndLocation;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.widget.Toast;
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.CameraPosition;
import com.google.android.gms.maps.model.Circle;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import com.teledaktar.R;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.Marker;
import com.teledaktar.activities.blogActivities.BlogActivity;
import com.teledaktar.activities.root.MainActivity;
import com.teledaktar.api.AppClient;
import com.teledaktar.api.ApplicationConfig;
import com.teledaktar.model.blog.BlogContent;
import com.teledaktar.model.hospital_model.Hospital;
import com.teledaktar.model.nearestHospitalModels.Hospitals;
import com.teledaktar.model.nearestHospitalModels.NearestHospitalContent;
import com.teledaktar.utility.Constants;
import java.util.ArrayList;
import dmax.dialog.SpotsDialog;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class DoctorLocationOnMapsActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener, SensorEventListener, GoogleMap.OnMarkerClickListener {
private GoogleMap mMap;
GoogleApiClient mGoogleApiClient;
LocationRequest mLocationRequest;
Location mLastLocation;
Marker mCurrLocationMarker;
double currentLatitude, currentLongitude;
float mDeclination;
private SpotsDialog pDialog;
private Marker myMarker;
int clickPosition;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_doctor_location_on_maps);
pDialog = new SpotsDialog(DoctorLocationOnMapsActivity.this, R.style.Custom);
pDialog.setCancelable(true);
checkLocationPermission();
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
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));
buildGoogleApiClient();
if (ActivityCompat.checkSelfPermission(DoctorLocationOnMapsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(DoctorLocationOnMapsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)) {
mMap.setMyLocationEnabled(true);
}
}
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
// mMap.setMyLocationEnabled(true);
return;
}
// Toast.makeText(this, Double.toString(currentLattitude), Toast.LENGTH_SHORT).show();
//specify latitude and longitude of both source and destination
/*Polyline line = googleMap.addPolyline(new PolylineOptions()
.add(new LatLng(currentLattitude, currentLongitude), new LatLng(24.21,88.84))
.width(10)
.color(Color.MAGENTA));
*/
mMap.setOnMarkerClickListener(this);
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
return;
}
String lattitudeString = Constants.latitude;
String longitudeString = Constants.longitude;
if (lattitudeString == null) {
lattitudeString = "23.7277";
}
if (longitudeString == null) {
longitudeString = "90.4106";
}
Double hospitalLat = Double.parseDouble(lattitudeString);
Double hospitalLong = Double.parseDouble(longitudeString);
/*
LatLng bagha = new LatLng(hospitalLat,hospitalLong);
mMap.addMarker(new MarkerOptions().position(bagha).title("Marker in Hospital"));*/
/**
* find current location . latitude and longitude
*/
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation == null) {
Toast.makeText(this, "Please Enable GPS and give location permission to get dirrection ", Toast.LENGTH_SHORT).show();
} else {
currentLatitude = mLastLocation.getLatitude();
currentLongitude = mLastLocation.getLongitude();
getNearestHospitalApiData(currentLatitude, currentLongitude);
/* Polyline line = mMap.addPolyline(new PolylineOptions()
.add(new LatLng(currentLatitude, currentLongitude), new LatLng(hospitalLat, hospitalLong))
.width(10)
.color(Color.GREEN));
*/
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#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_BLUE));
mCurrLocationMarker = mMap.addMarker(markerOptions);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(12));
//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission() {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
}
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) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
return;
}
} else {
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
}
}
/*
for changing auto rotation
*/
#Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ROTATION_VECTOR) {
float[] rotMat = new float[9];
float[] rotMat1 = new float[9];
SensorManager.getRotationMatrixFromVector(
rotMat, event.values);
float[] orientation = new float[3];
SensorManager.getOrientation(rotMat, orientation);
float bearing = (float) (Math.toDegrees(orientation[0]) + mDeclination);
updateCamera(bearing);
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
private void updateCamera(float bearing) {
CameraPosition oldPos = mMap.getCameraPosition();
CameraPosition pos = CameraPosition.builder(oldPos).bearing(bearing).build();
mMap.moveCamera(CameraUpdateFactory.newCameraPosition(pos));
}
public void getNearestHospitalApiData(Double latitude, Double longitude) {
/**
* HERE API CALL WILL BE ADDED
*/
show();
String lats = Double.toString(latitude);
String longs = Double.toString(longitude);
final ApplicationConfig apiServiceReader = AppClient.getApiService();
Call<NearestHospitalContent> list = apiServiceReader.getNearestHospitals(lats, longs);
list.enqueue(new Callback<NearestHospitalContent>() {
#Override
public void onResponse(Call<NearestHospitalContent> call, Response<NearestHospitalContent> response) {
if (response.isSuccessful()) {
hide();
if (response.body().getStatus_code().equals("200")){
ArrayList<Hospitals> nearestHospitals = response.body().getHospitals();
if (nearestHospitals.size() > 0) {
for (int i = 0; i < nearestHospitals.size(); i++) {
Double latitudes = Double.parseDouble(nearestHospitals.get(i).getLatitude().substring(0, 5));
Double longitudes = Double.parseDouble(nearestHospitals.get(i).getLongitude().substring(0, 5));
LatLng hospitalMarker = new LatLng(latitudes, longitudes);
myMarker = mMap.addMarker(new MarkerOptions()
.position(hospitalMarker)
.title(nearestHospitals.get(i).getName())
.snippet(nearestHospitals.get(i).getDescription())
.alpha(0.8f)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
// mMap.addMarker(new MarkerOptions().position(hospitalMarker).title(nearestHospitals.get(i).getName()).alpha(0.8f));
myMarker.showInfoWindow();
Constants.NEAREST_HOSPITAL_NAME = nearestHospitals.get(i).getName();
clickPosition =i;
System.out.println("clicked"+i);
}
}else {
Toast.makeText(DoctorLocationOnMapsActivity.this, "Currently No Nearest Hospital found at this position ", Toast.LENGTH_SHORT).show();
}
}
} else {
hide();
Toast.makeText(DoctorLocationOnMapsActivity.this, "not success", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<NearestHospitalContent> call, Throwable t) {
hide();
Toast.makeText(DoctorLocationOnMapsActivity.this, "Failed", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onMarkerClick(final Marker marker) {
Toast.makeText(DoctorLocationOnMapsActivity.this,Integer.toString(clickPosition), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(DoctorLocationOnMapsActivity.this,MainActivity.class);
startActivity(intent);
}
/* Integer clickCount = (Integer) marker.getTag();
if (clickCount != null) {
clickCount = clickCount + 1;
marker.setTag(clickCount);
Toast.makeText(this,
marker.getTitle() +
" has been clicked " + clickCount + " times.",
Toast.LENGTH_SHORT).show();
}*/
return false;
}
private void show() {
pDialog.show();
pDialog.setMessage(getString(R.string.waiting_data_string));
}
private void hide() {
pDialog.dismiss();
}
}