Skip to main content

How to create google map with drag marker to get user location with auto correct location edit text ...


For drag and drop with user location You have to create a google map fragment activity

below are the xml code of google map xml

<?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=".GetUserLocationActivity">


    <fragment        android:id="@+id/mapuserloc"        android:name="com.google.android.gms.maps.SupportMapFragment"        android:layout_width="match_parent"        android:layout_height="522dp"        app:layout_constraintEnd_toEndOf="parent"        app:layout_constraintStart_toStartOf="parent"        app:layout_constraintTop_toTopOf="parent" />


    <androidx.cardview.widget.CardView        android:id="@+id/idCardView"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_marginStart="16dp"        android:layout_marginTop="18dp"        android:layout_marginEnd="16dp"        app:cardCornerRadius="8dp"        android:elevation="10dp"        app:layout_constraintEnd_toEndOf="parent"        app:layout_constraintStart_toStartOf="parent"        app:layout_constraintTop_toTopOf="parent">

        <fragment            android:id="@+id/autocomplete_fragment"            android:name="com.google.android.libraries.places.widget.AutocompleteSupportFragment"            android:layout_width="match_parent"            android:layout_height="wrap_content" />

    </androidx.cardview.widget.CardView>

    <androidx.constraintlayout.widget.ConstraintLayout        android:id="@+id/linearLayout2"        android:layout_width="match_parent"        android:layout_height="0dp"        android:elevation="10dp"        android:background="@color/white"        app:layout_constraintBottom_toBottomOf="parent"        app:layout_constraintEnd_toEndOf="parent"        app:layout_constraintHorizontal_bias="1.0"        app:layout_constraintStart_toStartOf="parent"        app:layout_constraintTop_toBottomOf="@+id/mapuserloc">

        <!--        <TextView-->        <!--            android:id="@+id/textView28"-->        <!--            android:layout_width="match_parent"-->        <!--            android:layout_height="wrap_content"-->        <!--            android:text="TextView" />-->

        <TextView            android:id="@+id/movemarker"            android:layout_width="0dp"            android:layout_height="wrap_content"            android:layout_marginStart="16dp"            android:layout_marginTop="16dp"            android:layout_marginEnd="16dp"            android:layout_weight="1"            android:fontFamily="@font/lato_medium"            android:padding="3dp"            android:text="MOVE MARKER TO SET LOCATION"            android:textColor="@color/extraLightBlack"            android:textSize="10sp"            app:layout_constraintEnd_toEndOf="parent"            app:layout_constraintHorizontal_bias="0.0"            app:layout_constraintStart_toStartOf="parent"            app:layout_constraintTop_toTopOf="parent" />

        <TextView            android:id="@+id/area"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_marginStart="16dp"            android:fontFamily="@font/lato_heavy"            android:padding="3dp"            android:text="Locating ..."            android:textColor="@color/black"            android:textSize="22sp"            android:textStyle="bold"            app:layout_constraintStart_toStartOf="parent"            app:layout_constraintTop_toBottomOf="@+id/movemarker" />

        <TextView            android:id="@+id/fullAdress"            android:layout_width="0dp"            android:layout_height="wrap_content"            android:layout_marginEnd="16dp"            android:layout_weight="1"            android:fontFamily="@font/lato_regular"            android:padding="3dp"            android:text="..."            android:maxLines="3"            android:ellipsize="end"            android:textColor="@color/mediumBlack"            android:textSize="14sp"            app:layout_constraintEnd_toEndOf="parent"            app:layout_constraintStart_toStartOf="@+id/area"            app:layout_constraintTop_toBottomOf="@+id/area" />

        <Button            android:id="@+id/btn_userloc"            android:layout_width="match_parent"            android:layout_height="50dp"            android:layout_marginStart="16dp"            android:layout_marginEnd="16dp"            android:layout_marginBottom="18dp"            android:background="@drawable/locate_button"            android:text="Confirm Location"            android:textSize="13sp"            app:layout_constraintBottom_toBottomOf="parent"            app:layout_constraintEnd_toEndOf="parent"            app:layout_constraintStart_toStartOf="parent" />

    </androidx.constraintlayout.widget.ConstraintLayout>

    <ImageView        android:id="@+id/imageView7"        android:layout_width="32dp"        android:layout_height="35dp"        android:layout_marginBottom="34dp"        app:layout_constraintBottom_toBottomOf="@+id/mapuserloc"        app:layout_constraintEnd_toEndOf="parent"        app:layout_constraintStart_toStartOf="@+id/mapuserloc"        android:contentDescription="shoop look user location image"        app:layout_constraintTop_toTopOf="@+id/mapuserloc"        app:srcCompat="@drawable/ic_placeholder" />


</androidx.constraintlayout.widget.ConstraintLayout>



Then create java class for  it 

like this 

package in.shoplook.shoplookUser;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;


import com.google.android.gms.common.api.Status;

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.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.libraries.places.api.Places;
import com.google.android.libraries.places.api.model.Place;
import com.google.android.libraries.places.api.net.PlacesClient;
import com.google.android.libraries.places.widget.AutocompleteSupportFragment;
import com.google.android.libraries.places.widget.listener.PlaceSelectionListener;


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

import im.delight.android.location.SimpleLocation;

public class GetUserLocationActivity extends AppCompatActivity implements OnMapReadyCallback  {

    private GoogleMap mMap;
    View mapView;
    private SimpleLocation location;
    LatLng userLocation;
    Marker currentmarker;
    TextView area, fullAdress;
    String TAG = "GetUserLoca";
    Button btn_userloc;
    Intent intent;
    ShopLook app;
    double platitude , plongitude;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_get_user_location);
        location = new SimpleLocation(this);
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.mapuserloc);
        mapView = mapFragment.getView();
        mapFragment.getMapAsync(this);
        app = (ShopLook) getApplication();
        fullAdress = findViewById(R.id.fullAdress);
        area = findViewById(R.id.area);

        // Initialize the AutocompleteSupportFragment.        AutocompleteSupportFragment autocompleteFragment = (AutocompleteSupportFragment)
                getSupportFragmentManager().findFragmentById(R.id.autocomplete_fragment);
        autocompleteFragment.getView().setBackgroundColor(getResources().getColor(R.color.white));

        btn_userloc  = findViewById(R.id.btn_userloc);
        btn_userloc.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {

                intent = new Intent();
                Log.d(TAG, "onCreatelatLong" + platitude + "longitude"+plongitude);
                app.saveIntoPrefs("User_address" , fullAdress.getText().toString());
                app.saveDoubleIntoPrefs("latitude" , platitude);
                app.saveDoubleIntoPrefs("longitude",plongitude);
                intent.putExtra("fulladdress", fullAdress.getText().toString());
                setResult(300, intent);
                finish();
            }
        });
        Places.initialize(getApplicationContext(), "AIzaSyCapAUHyXfl64wsdoKESgDMIrFCembNeoA");

// Create a new Places client instance        PlacesClient placesClient = Places.createClient(this);
        // Specify the types of place data to return.        autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.LAT_LNG));

// Set up a PlaceSelectionListener to handle the response.        autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
            @Override            public void onPlaceSelected(Place place) {
                // TODO: Get info about the selected place.                LatLng nlatlong = place.getLatLng();
                Log.d(TAG, "onPlaceSelected: " + place.getAddress());

                mMap.clear();

//                mMap.addMarker(new MarkerOptions().position(nlatlong));                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(nlatlong, 16));
                Log.i(TAG, "Place: " + place.getName() + ", " + place.getId());
            }

            @Override            public void onError(Status status) {
                // TODO: Handle the error.                Log.i(TAG, "An error occurred: " + status);
            }
        });

    }


    @Override    public void onMapReady(GoogleMap googleMap) {

        mMap = googleMap;
        mMap.setMyLocationEnabled(true);

//        LatLng sydney = new LatLng(-34, 151);//        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));//        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
        View locationButton = ((View) mapView.findViewById(Integer.parseInt("1")).getParent()).findViewById(Integer.parseInt("2"));
        RelativeLayout.LayoutParams rlp = (RelativeLayout.LayoutParams) locationButton.getLayoutParams();
// position on right bottom        rlp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, 0);
        rlp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
        rlp.setMargins(0, 1000, 180, 0);
//        if(app.getDoubleFromPrefs("latitude") != 0.0)//        {//            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(app.getDoubleFromPrefs("latitude"), app.getDoubleFromPrefs("longitude")), 15.0f));//        }
            userLocation = new LatLng(location.getLatitude(), location.getLongitude());
            final MarkerOptions curentoption = new MarkerOptions();
            curentoption.position(userLocation).title("your location");
            currentmarker = mMap.addMarker(curentoption);
            currentmarker.setVisible(false);
            if(app.getDoubleFromPrefs("latitude") != 0.0)
            {
                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(app.getDoubleFromPrefs("latitude"), app.getDoubleFromPrefs("longitude")), 15.0f));
            }
            else {
                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 15.0f));
            }
            mMap.setOnCameraIdleListener(new GoogleMap.OnCameraIdleListener() {
                @Override                public void onCameraIdle() {

                    if (currentmarker != null) {
                        LatLng center = mMap.getCameraPosition().target;
                        getAddressFromLocation(center.latitude, center.longitude, GetUserLocationActivity.this, new GeocoderHandler());

                    }

                }
            });

    }

    public static void getAddressFromLocation(final double latitude, final double longitude,
                                              final Context context, final Handler handler) {
        Thread thread = new Thread() {
            @Override            public void run() {
                Geocoder geocoder = new Geocoder(context, Locale.getDefault());
                String result = null;
                String subloc ="";
                try {
                    List<Address> addressList = geocoder.getFromLocation(
                            latitude, longitude, 1);
                    if (addressList != null && addressList.size() > 0) {
                        Address address = addressList.get(0);
                        String TAG = "loc";
                        Log.d(TAG, "run: " + address);
                        StringBuilder sb = new StringBuilder();
                        for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
                            sb.append(address.getAddressLine(i)).append("\n");
                        }

                        sb.append(address.getAddressLine(0)).append("\n");
                        subloc = address.getSubLocality();
//                        sb.append(address.getLocality()).append("\n");//                        sb.append(address.getPostalCode()).append("\n");//                        sb.append(address.getCountryName());                        result = sb.toString();
                    }
                } catch (IOException e) {
//                    Log.e(TAG, "Unable connect to Geocoder", e);                } finally {
                    Message message = Message.obtain();
                    message.setTarget(handler);
                    if (result != null) {
                        message.what = 1;
                        Bundle bundle = new Bundle();
                        result = result;
                        bundle.putString("address", result);
                        bundle.putString("sublloc", subloc);
                        bundle.putDouble("latitude" , latitude);
                        bundle.putDouble("longitude" , longitude);
                        message.setData(bundle);
                    } else {
                        message.what = 1;
                        Bundle bundle = new Bundle();
                        result = "Latitude: " + latitude + " Longitude: " + longitude +
                                "\n Unable to get address for this lat-long.";
                        bundle.putString("address", result);
                        message.setData(bundle);
                    }
                    message.sendToTarget();
                }
            }
        };
        thread.start();

}

    @Override    public void onBackPressed() {


//        intent = new Intent();//        intent.putExtra("fulladdress", fullAdress.getText().toString());////        setResult(3000, intent);//        finish();        super.onBackPressed();
    }

//    @Override//    public void onTextClear() {////    }
//    @Override//    public void onItemSelected(Place selectedPlace) {////        mMap.clear();//        mMap.addMarker(new MarkerOptions().position(selectedPlace.getLatLng()));//        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(selectedPlace.getLatLng(), 16));//    }
    private class GeocoderHandler extends Handler {
        @Override        public void handleMessage(Message message) {
            String locationAddress;
            String subloc="not found";
//            double latitude = Double.parseDouble(null);//            double longitude = Double.parseDouble(null);            switch (message.what) {
                case 1:
                    Bundle bundle = message.getData();
                    locationAddress = bundle.getString("address");
                    subloc = bundle.getString("sublloc");
                    platitude = bundle.getDouble("latitude");
                    plongitude = bundle.getDouble("longitude");
                    break;
                default:
                    locationAddress = null;
            }
            Log.d(TAG, "handleMessage: "+ locationAddress);
            if(subloc != null) {
                area.setText(subloc);
                fullAdress.setText(locationAddress);
//                platitude = latitude;//                plongitude = longitude;            }
            else{
                area.setText("Locating");
                fullAdress.setText("...");
            }
        }
    }
}

for this you need following depandancy 

below are the depandancy :

implementation 'com.google.code.gson:gson:2.3.1'
implementation 'com.google.android.gms:play-services-maps:17.0.0'
implementation 'com.github.delight-im:Android-SimpleLocation:v1.0.1'
implementation 'com.google.android.gms:play-services-places:17.0.0'implementation 'com.google.android.libraries.places:places:2.0.0'

Comments

Popular posts from this blog

how to create chat gpt app in android with java code

  I'd be happy to provide you with some sample Java code for a chat GPT app in Android, however it is important to note that creating a complete and functional app requires a solid understanding of Android development, Java and OpenAI API, and also the code I provide here is just a skeleton or a sample of what it would look like in practice. You would need to import the OpenAI API library and configure it with your API key. Here is an example of how you might use the OpenAI Java client library to send user input to the GPT-3 model and receive the generated response: import openai.OpenAI; public class ChatGPT { private OpenAI openai; private String apiKey = "YOUR_API_KEY"; public ChatGPT() { openai = new OpenAI(apiKey); } public String generateResponse(String input) { String response = ""; try { response = openai.completions().create() .engine("text-davinci-002")

how to send user location in background android code

  To send a user's location in the background in an Android application, you can use the FusedLocationProviderClient class to request location updates and the Service class to run a background service that can perform the location updates and send the data to your server or another destination. Here is an example of how to set up a background service that requests location updates every 5 minutes: Create a new service class that extends Service , for example LocationUpdateService . In the onCreate() method of the service, initialize the FusedLocationProviderClient and request location updates using the requestLocationUpdates() method. FusedLocationProviderClient fusedLocationClient; @Override public void onCreate() {     super.onCreate();     fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);     fusedLocationClient.requestLocationUpdates(             getLocationRequest(),             locationCallback,             Looper.getMainLooper()); } Implement