Tutorial 14 - Get Current Location with Marker

 


This is Sample Project Which you can improve UI design & Coding skills .

1) First you need New Empty Activity.(MapActivity)

MapActivity

package com.rrmchathura.myfirstapp;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Camera;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.media.audiofx.BassBoost;
import android.net.Uri;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.provider.Settings;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.internal.GoogleApiAvailabilityCache;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.maps.CameraUpdate;
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.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionDeniedResponse;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.single.PermissionListener;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

public class MapActivity extends AppCompatActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

boolean isPermissionGranted;
GoogleMap mGoogleMap;
FloatingActionButton fab;
private FusedLocationProviderClient mLocationClient;
private int GPS_REQUEST_CODE = 9001;

EditText locSearch;
ImageView searchIcon;



@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);

fab = findViewById(R.id.fab);
locSearch = findViewById(R.id.et_search);
searchIcon = findViewById(R.id.search_icon);

checkPermission();

initMap();

mLocationClient = new FusedLocationProviderClient(this);

fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getCurrentLoc();
}
});
searchIcon.setOnClickListener(this::geoLocate);

}

private void geoLocate(View view) {
String locationName = locSearch.getText().toString();
Geocoder geocoder = new Geocoder(this, Locale.getDefault());

try {
List<Address> addressList = geocoder.getFromLocationName(locationName,1);
if (addressList.size()>0){
Address address = addressList.get(0);

gotoLocation(address.getLatitude(),address.getLongitude());

mGoogleMap.addMarker(new MarkerOptions().position(new LatLng(address.
getLatitude(),address.getLongitude())));
Toast.makeText(MapActivity.this, address.getLocality(),
Toast.LENGTH_SHORT).show();
}

} catch (IOException e) {

}
}

private void initMap() {
if (isPermissionGranted){
if (isGPSenable()){
SupportMapFragment supportMapFragment = (SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.fragment);
supportMapFragment.getMapAsync(this);
}
}

}

private boolean isGPSenable(){
LocationManager locationManager = (LocationManager) getSystemService
(LOCATION_SERVICE);

boolean providerEnable = locationManager.isProviderEnabled(LocationManager.
GPS_PROVIDER);
if (providerEnable){
return true;
}else {
AlertDialog alertDialog = new AlertDialog.Builder(this).setTitle
("GPS Permission")
.setMessage("GPS is required for this app to work").
setPositiveButton("Yes",((dialogInterface,i)->{
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(intent, GPS_REQUEST_CODE);
}))
.setCancelable(false).show();



}


return false;
}

@SuppressLint("MissingPermission")
private void getCurrentLoc() {
mLocationClient.getLastLocation().addOnCompleteListener(task -> {
if (task.isSuccessful()){
Location location = task.getResult();
gotoLocation(location.getLatitude(),location.getLongitude());
mGoogleMap.addMarker(new MarkerOptions().position(
new LatLng(location.getLatitude(),location.getLongitude())));

}
});
}

private void gotoLocation(double latitude, double longitude) {
LatLng LatLng = new LatLng(latitude,longitude);

CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(LatLng,18);
mGoogleMap.moveCamera(cameraUpdate);
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}


private void checkPermission() {

Dexter.withContext(this).withPermission(Manifest.permission.
ACCESS_FINE_LOCATION).withListener(new PermissionListener() {
@Override
public void onPermissionGranted(PermissionGrantedResponse
permissionGrantedResponse) {
Toast.makeText(MapActivity.this,"Permission Granted",
Toast.LENGTH_SHORT).show();
isPermissionGranted = true;
}

@Override
public void onPermissionDenied(PermissionDeniedResponse permissionDeniedResponse)
{
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package",getPackageName(),"");
intent.setData(uri);
startActivity(intent);
}

@Override
public void onPermissionRationaleShouldBeShown
(PermissionRequest permissionRequest,
PermissionToken permissionToken) {
permissionToken.continuePermissionRequest();
}
}).check();
}

@SuppressLint("MissingPermission")
@Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
// mGoogleMap.setMyLocationEnabled(true);
}

@Override
public void onConnected(Bundle bundle) {

}

@Override
public void onConnectionSuspended(int i) {

}


@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {}

@Override
protected void onActivityResult(int requestCode, int resultCode,
@Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==GPS_REQUEST_CODE){
LocationManager locationManager = (LocationManager)
getSystemService(LOCATION_SERVICE);
boolean providerEnable = locationManager.isProviderEnabled
(LocationManager.GPS_PROVIDER);

if (providerEnable){
Toast.makeText(MapActivity.this,"GPS is enable",
Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(MapActivity.this,"GPS is not enable",
Toast.LENGTH_SHORT).show();
}
}

}

public void backbtn(View view) {
Intent intent = new Intent(MapActivity.this,HomeActivity.class);
startActivity(intent);
}
}


activity_layout

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MapActivity">

<EditText
android:id="@+id/et_search"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintHorizontal_bias="0"
app:layout_constraintVertical_bias="0"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>

<ImageView
android:id="@+id/search_icon"
android:layout_width="60dp"
android:layout_height="wrap_content"
android:src="@drawable/ic_search"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1"
app:layout_constraintBottom_toBottomOf="@+id/et_search"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>

<fragment
android:id="@+id/fragment"
class="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintVertical_bias="0.0"
app:layout_constraintTop_toBottomOf="@id/et_search"
/>

<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintHorizontal_bias="1"
android:src="@drawable/ic_location"
android:scaleType="centerCrop"
app:layout_constraintVertical_bias="1"
android:layout_margin="16dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/fab1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintHorizontal_bias="0"
android:src="@drawable/ic_arrow_back"
android:scaleType="centerCrop"
android:onClick="backbtn"
app:layout_constraintVertical_bias="1"
android:layout_margin="16dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />




</androidx.constraintlayout.widget.ConstraintLayout>


Post a Comment

0 Comments

Youtube Channel Image
Coding With Chathura Subscribe To watch more Project Tutorials
Subscribe
Do you have any doubts? chat with us on WhatsApp
Hello, How can I help you? ...
Click me to start the chat...

Welcome to freesourcecodelk

X