user3623979
user3623979

Reputation:

How to move map under a marker? android

I want to implement the drag effect of a map. When we drag the map the marker should show the current position or latitude and longitude. Its done in Uber application see below: enter image description here

In this marker shows the current location as the map is dragged. How can I achieve this???

ChooseFromMapActivity

    public class ChooseFromMapActivity extends AppCompatActivity implements GoogleMap.OnCameraChangeListener {

    TextView textShowAddress;
    private GoogleMap mMap;
    LatLng latLng;
    double latitude = 17.385044;
    double longitude = 78.486671;
    float zoom;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choose_from_map);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mMap = mapFragment.getMap();
        mMap.setMyLocationEnabled(true);
        LatLng center = mMap.getCameraPosition().target;
        mMap.getUiSettings().setZoomControlsEnabled(true);
        mMap.getUiSettings().setRotateGesturesEnabled(true);
        mMap.getUiSettings().setScrollGesturesEnabled(true);
        latLng = new LatLng(-34, 151);

     mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

        textShowAddress = (TextView) findViewById(R.id.textShowAddress);
        mMap.addMarker(new MarkerOptions()
                .position(latLng)
                .draggable(false)
                .title("sent location :)"))
        .setDraggable(false);
        }
    }
}

Upvotes: 0

Views: 5495

Answers (3)

AUPMA
AUPMA

Reputation: 304

Since setOnCameraChangeListener has depricated, You Can get same effect by placing image view with same marker at center of map and useing setOnCameraIdleListener with setOnCameraMoveListener

private Marker tempMarker;
private SupportMapFragment mapFragment;

private void addMapListeners() {
        mapFragment.getMapAsync((googleMap -> {
            googleMap.setOnCameraIdleListener(() -> {
                LatLng target = googleMap.getCameraPosition().target;
                addMarker(target);
            });
            googleMap.setOnCameraMoveListener(()->{
                tempMarker.remove();
            });
        }));
    }

private void addMarker(LatLng markerPosition) {
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(markerPosition);

        mapFragment.getMapAsync((googleMap -> {
            if (tempMarker != null) {
                tempMarker.remove();
            }
            tempMarker = googleMap.addMarker(markerOptions);
        }));
    }

Google Map Image (Run time)

Add Image View (Android Studio)

Upvotes: 0

abalta
abalta

Reputation: 1257

The answer is good but, setOnCameraChangeListener has depreciated. Use setOnCameraIdleListener.

Here some example to get camera position of map.

    mMap.setOnCameraIdleListener(new GoogleMap.OnCameraIdleListener() {
        @Override
        public void onCameraIdle() {
            LatLng midLatLng = mMap.getCameraPosition().target;
            getAddress(midLatLng.latitude, midLatLng.longitude);
        }
    });

Now, getAddress returns to centered position of address.

Upvotes: 2

Jay Thummar
Jay Thummar

Reputation: 2299

Some people are confused how to solve this here is the simple solution step 1: create a layout with google map frame and one image view in the center

    <FrameLayout
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/btn_save" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:src="@drawable/pin" /> 

Step 2 : Create method initialize map and put it in onCreate()... means in the starting of the activity so it will initialize the map frame...here you need to create an instance of SupportMapFragment

/*==================== initialize map fragment  ==================*/


private void initilizeMap() {

        mSupportMapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map_profile);

        if (mSupportMapFragment == null) {
            FragmentManager fragmentManager = getChildFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            mSupportMapFragment = SupportMapFragment.newInstance();
            fragmentTransaction.replace(R.id.map_profile, mSupportMapFragment).commit();
        }

        Log.d("mSupportMapFragment", "------" + mSupportMapFragment + "-----googleMap---" + googleMap);
    }

Step3 : Now Create an Instance of LatLng (private LatLng latlng) (It will return the centered latitude and longitude of your map and the image which we have it also in the center so it seems like the marker image which we have is returning the latitude and langitude )

Step 4: Create a method IniLizeMap(); which will set the attributes and loation in to map.

public void IniLizeMap() {
        try {
            mSupportMapFragment.getMapAsync(new OnMapReadyCallback() {
                @Override
                public void onMapReady(GoogleMap googleMap) {

                    googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

                    // Showing / hiding your current location
                    googleMap.setMyLocationEnabled(false);

                    // Enable / Disable zooming controls
                    googleMap.getUiSettings().setZoomControlsEnabled(false);

                    // Enable / Disable my location button
                    googleMap.getUiSettings().setMyLocationButtonEnabled(false);

                    // Enable / Disable Compass icon
                    googleMap.getUiSettings().setCompassEnabled(false);

                    // Enable / Disable Rotate gesture`enter code here`
                    googleMap.getUiSettings().setRotateGesturesEnabled(false);

                    // Enable / Disable zooming functionality
                    googleMap.getUiSettings().setZoomGesturesEnabled(false);   

                    googleMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
                        @Override
                        public void onCameraChange(CameraPosition cameraPosition) {
                            latLng = cameraPosition.target;
                            googleMap.clear();
                            try {
                                getAddress(latLng.latitude, latLng.longitude);
                                Log.e("Changing address", getAddress(latLng.latitude, latLng.longitude));
                                Log.e("Latitude", latLng.latitude + "");
                                Log.e("Longitude", latLng.longitude + "");
                                String lat = latLng.latitude + "";
                                String lng = latLng.longitude + "";
                                String location = getAddress(latLng.latitude, latLng.longitude);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });                 



                    CameraPosition cameraPosition = new CameraPosition.Builder()
                            .target(new LatLng(Double.parseDouble(Utils.lat),
                                    Double.parseDouble(Utils.lng))).zoom(14).build();

                    googleMap.animateCamera(CameraUpdateFactory
                            .newCameraPosition(cameraPosition));
                }


            });

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

In this method i apply setOnCameraChangeListener to googlemap that is the mian core solution of our problem which will return the centered location while moving the camera and now if you want to get the addres while it moving then create the method getAddress which will return string address while moving the map so here it is

Step 5: create method getAddress(double lat,double lng) which required two dubbles

 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();
    }

==================== That's it You map like UBER is ready =============

Upvotes: 6

Related Questions