Created
February 24, 2020 09:21
-
-
Save amirul12/1017c1a8e59b5fc00dd7bb875677a434 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.syntax.gtcl.ui.activity.gmap; | |
import androidx.annotation.NonNull; | |
import androidx.appcompat.app.AppCompatActivity; | |
import androidx.appcompat.widget.Toolbar; | |
import androidx.core.app.ActivityCompat; | |
import androidx.core.content.ContextCompat; | |
import androidx.fragment.app.FragmentActivity; | |
import android.Manifest; | |
import android.annotation.SuppressLint; | |
import android.content.pm.PackageManager; | |
import android.location.Address; | |
import android.location.Geocoder; | |
import android.location.Location; | |
import android.os.Bundle; | |
import android.util.Log; | |
import android.view.Menu; | |
import android.view.MenuItem; | |
import android.view.View; | |
import android.widget.AdapterView; | |
import android.widget.ArrayAdapter; | |
import android.widget.ListView; | |
import com.google.android.gms.common.api.ApiException; | |
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.CameraPosition; | |
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 com.google.android.gms.tasks.OnCompleteListener; | |
import com.google.android.gms.tasks.Task; | |
import com.google.android.libraries.places.api.Places; | |
import com.google.android.libraries.places.api.model.Place; | |
import com.google.android.libraries.places.api.model.PlaceLikelihood; | |
import com.google.android.libraries.places.api.net.FindCurrentPlaceRequest; | |
import com.google.android.libraries.places.api.net.FindCurrentPlaceResponse; | |
import com.google.android.libraries.places.api.net.PlacesClient; | |
import com.syntax.gtcl.R; | |
import java.io.IOException; | |
import java.util.Arrays; | |
import java.util.List; | |
import java.util.Locale; | |
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback { | |
private static final String TAG = "MapsActivity"; | |
ListView listPlace; | |
private PlacesClient mPlacesClient; | |
private FusedLocationProviderClient mFusedLocationProviderClient; | |
private Location mLastKnownLocation; | |
private final LatLng mDefaultLocation = new LatLng(-34, 151); | |
private static final int DEFAUTL_ZOOM = 15; | |
private static final int PERMISSION_REQUEST_ACTION_FIND_LOCATION = 1; | |
private boolean mLocationPermissionGranted; | |
/*selecting the current location*/ | |
private static final int M_MAX_ENTERIES = 5; | |
private String[] mLikelyPlaceNames; | |
private String[] mLikelyPlaceAddresses; | |
private String[] mLikelyPlaceAttributions; | |
private LatLng[] mLikelyPlaceLatLngs; | |
private GoogleMap mMap; | |
private Marker currentMarker; | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_maps); | |
// Obtain the SupportMapFragment and get notified when the map is ready to be used. | |
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() | |
.findFragmentById(R.id.map); | |
mapFragment.getMapAsync(this); | |
/*setup the view*/ | |
/*SET UP THE ACTION BAR*/ | |
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); | |
setSupportActionBar(toolbar); | |
listPlace = (ListView) findViewById(R.id.listPlaces); | |
// Initialize the Places client | |
String apiKey = getString(R.string.google_maps_key); | |
Places.initialize(getApplicationContext(), apiKey); | |
mPlacesClient = Places.createClient(this); | |
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this); | |
} | |
/** | |
* Manipulates the map once available. | |
* This callback is triggered when the map is ready to be used. | |
* This is where we can add markers or lines, add listeners or move the camera. In this case, | |
* we just add a marker near Sydney, Australia. | |
* If Google Play services is not installed on the device, the user will be prompted to install | |
* it inside the SupportMapFragment. This method will only be triggered once the user has | |
* installed Google Play services and returned to the app. | |
*/ | |
@Override | |
public void onMapReady(GoogleMap googleMap) { | |
mMap = googleMap; | |
// 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.getUiSettings().setZoomControlsEnabled(true); | |
MarkerOptions options = new MarkerOptions(); | |
// currentMarker = mMap.addMarker(options); | |
getLocationPermission(); | |
mMap.setOnCameraIdleListener(new GoogleMap.OnCameraIdleListener() { | |
@Override | |
public void onCameraIdle() { | |
LatLng center = mMap.getCameraPosition().target; | |
if (currentMarker != null){ | |
currentMarker.remove(); | |
mMap.addMarker(new MarkerOptions().position(center).title("new position ")); | |
} | |
getAddress(center.latitude, center.longitude); | |
} | |
}); | |
} | |
@Override | |
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { | |
super.onRequestPermissionsResult(requestCode, permissions, grantResults); | |
mLocationPermissionGranted = false; | |
switch (requestCode){ | |
case PERMISSION_REQUEST_ACTION_FIND_LOCATION:{ | |
/*if request is cancelled, the request array is empty*/ | |
if (grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){ | |
mLocationPermissionGranted = true; | |
} | |
} | |
} | |
} | |
@Override | |
public boolean onCreateOptionsMenu(Menu menu) { | |
getMenuInflater().inflate(R.menu.menu, menu); | |
return super.onCreateOptionsMenu(menu); | |
} | |
@Override | |
public boolean onOptionsItemSelected(MenuItem item) { | |
switch (item.getItemId()) { | |
case R.id.action_geolocate: | |
//pick current place | |
pickCurrentPlace(); | |
default: | |
return super.onOptionsItemSelected(item); | |
} | |
} | |
private void pickCurrentPlace() { | |
if (mMap == null){ | |
return; | |
} | |
if (mLocationPermissionGranted){ | |
getDeviceLocation(); | |
}else { | |
/*the user has not granted permission*/ | |
Log.i(TAG, "The user did not grant location permission."); | |
mMap.addMarker(new MarkerOptions().title(getString(R.string.default_info_title)) | |
.position(mDefaultLocation) | |
.snippet(getString(R.string.default_info_snippet))); | |
getLocationPermission(); | |
} | |
} | |
private void getCurrentPlaceLikelihood(){ | |
//use plade field to define the data types to return. | |
List<Place.Field> placeField = Arrays.asList(Place.Field.NAME,Place.Field.ADDRESS, Place.Field.LAT_LNG); | |
/*get the likeli places - that is the bussiness and other point of interest that are the best match for | |
* the device current location | |
* */ | |
FindCurrentPlaceRequest request = FindCurrentPlaceRequest.builder(placeField).build(); | |
@SuppressLint("MissingPermission") | |
Task<FindCurrentPlaceResponse> placeResponseTask = mPlacesClient.findCurrentPlace(request); | |
placeResponseTask.addOnCompleteListener(this, new OnCompleteListener<FindCurrentPlaceResponse>() { | |
@Override | |
public void onComplete(@NonNull Task<FindCurrentPlaceResponse> task) { | |
if (task.isSuccessful()){ | |
FindCurrentPlaceResponse response = task.getResult(); | |
/*set the count , handles cases less then 5 entries are return*/ | |
int count; | |
if (response.getPlaceLikelihoods().size() < M_MAX_ENTERIES){ | |
count = response.getPlaceLikelihoods().size(); | |
}else { | |
count = M_MAX_ENTERIES; | |
} | |
int i = 0; | |
mLikelyPlaceNames = new String[count]; | |
mLikelyPlaceAddresses = new String[count]; | |
mLikelyPlaceAttributions = new String[count]; | |
mLikelyPlaceLatLngs = new LatLng[count]; | |
for (PlaceLikelihood placeLikelihood : response.getPlaceLikelihoods()){ | |
Place currPlace = placeLikelihood.getPlace(); | |
mLikelyPlaceNames[i] = currPlace.getName(); | |
mLikelyPlaceAddresses[i] = currPlace.getAddress(); | |
StringBuilder stringBuilder = new StringBuilder(); | |
stringBuilder.append(""+currPlace.getAttributions()); | |
mLikelyPlaceAttributions[i] = (currPlace.getAttributions() == null) ? null : stringBuilder.toString();mLikelyPlaceLatLngs[i] = currPlace.getLatLng(); | |
String currLatLng = (mLikelyPlaceLatLngs[i] == null) ? | |
"" : mLikelyPlaceLatLngs[i].toString(); | |
Log.i(TAG, String.format("Place " + currPlace.getName() | |
+ " has likelihood: " + placeLikelihood.getLikelihood() | |
+ " at " + currLatLng)); | |
i++; | |
if (i > (count - 1)) { | |
break; | |
} | |
} | |
fillPlacesList(); | |
}else { | |
Exception exception = task.getException(); | |
if (exception instanceof ApiException) { | |
ApiException apiException = (ApiException) exception; | |
Log.e(TAG, "Place not found: " + apiException.getStatusCode()); | |
} | |
} | |
} | |
}); | |
} | |
private void getDeviceLocation(){ | |
try { | |
if (mLocationPermissionGranted){ | |
Task<Location> locationResult = mFusedLocationProviderClient.getLastLocation(); | |
locationResult.addOnCompleteListener(new OnCompleteListener<Location>() { | |
@Override | |
public void onComplete(@NonNull Task<Location> task) { | |
if (task.isSuccessful()){ | |
/*set the map location position of the current location*/ | |
mLastKnownLocation = task.getResult(); | |
Log.d(TAG, "Latitude: " + mLastKnownLocation.getLatitude()); | |
Log.d(TAG, "Longitude: " + mLastKnownLocation.getLongitude()); | |
CameraPosition aCameraPosition = new CameraPosition.Builder().target( | |
new LatLng(mLastKnownLocation.getLatitude(), mLastKnownLocation.getLongitude())).zoom(15).build(); | |
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(aCameraPosition)); | |
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mLastKnownLocation.getLatitude(), mLastKnownLocation.getLongitude()),DEFAUTL_ZOOM)); | |
}else { | |
Log.d(TAG, "Current location is null. Using defaults."); | |
Log.e(TAG, "Exception: %s", task.getException()); | |
mMap.moveCamera(CameraUpdateFactory | |
.newLatLngZoom(mDefaultLocation, DEFAUTL_ZOOM)); | |
} | |
getCurrentPlaceLikelihood(); | |
} | |
}); | |
} | |
}catch (SecurityException e){ | |
Log.e("getDeviceLocation: %S ",e.getMessage()); | |
} | |
} | |
public String getAddress(double latitude, double longitude) { | |
StringBuilder result = new StringBuilder(); | |
try { | |
System.out.println("get address"); | |
Geocoder geocoder = new Geocoder(this, Locale.getDefault()); | |
List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1); | |
if (addresses.size() > 0) { | |
System.out.println("size====" + addresses.size()); | |
Address address = addresses.get(0); | |
for (int i = 0; i <= addresses.get(0).getMaxAddressLineIndex(); i++) { | |
if (i == addresses.get(0).getMaxAddressLineIndex()) { | |
result.append(addresses.get(0).getAddressLine(i)); | |
} else { | |
result.append(addresses.get(0).getAddressLine(i) + ","); | |
} | |
} | |
System.out.println("ad==" + address); | |
System.out.println("result---" + result.toString()); | |
// autoComplete_location.setText(result.toString()); // Here is you AutoCompleteTextView where you want to set your string address (You can remove it if you not need it) | |
} | |
} catch (IOException e) { | |
Log.e("tag", e.getMessage()); | |
} | |
return result.toString(); | |
} | |
private void getLocationPermission() { | |
/** | |
* Request location permission so that, we can get location of the device | |
* The result of the permission request handled by a callback, onRequestPermissionResult | |
*/ | |
mLocationPermissionGranted = false; | |
if (ContextCompat.checkSelfPermission(this.getApplicationContext(), | |
android.Manifest.permission.ACCESS_FINE_LOCATION) | |
== PackageManager.PERMISSION_GRANTED) { | |
mLocationPermissionGranted = true; | |
} else { | |
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_REQUEST_ACTION_FIND_LOCATION); | |
} | |
} | |
private AdapterView.OnItemClickListener listClickedHandler = new AdapterView.OnItemClickListener() { | |
public void onItemClick(AdapterView parent, View v, int position, long id) { | |
// position will give us the index of which place was selected in the array | |
LatLng markerLatLng = mLikelyPlaceLatLngs[position]; | |
String markerSnippet = mLikelyPlaceAddresses[position]; | |
if (mLikelyPlaceAttributions[position] != null) { | |
markerSnippet = markerSnippet + "\n" + mLikelyPlaceAttributions[position]; | |
} | |
// Add a marker for the selected place, with an info window | |
// showing information about that place. | |
mMap.addMarker(new MarkerOptions() | |
.title(mLikelyPlaceNames[position]) | |
.position(markerLatLng) | |
.snippet(markerSnippet)); | |
// Position the map's camera at the location of the marker. | |
mMap.moveCamera(CameraUpdateFactory.newLatLng(markerLatLng)); | |
} | |
}; | |
/** | |
* Display a list allowing the user to select a place from a list of likely places. | |
*/ | |
private void fillPlacesList() { | |
// Set up an ArrayAdapter to convert likely places into TextViews to populate the ListView | |
ArrayAdapter<String> placesAdapter = | |
new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mLikelyPlaceNames); | |
listPlace.setAdapter(placesAdapter); | |
listPlace.setOnItemClickListener(listClickedHandler); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment