Friday, November 1, 2019

Picking location with map pin using Google maps in Android

Step 1. import libary in build.gradle
implementation 'com.google.android.gms:play-services-maps:17.0.0'
implementation 'com.google.android.gms:play-services-location:17.0.0'
Step 2. creata a layout
<fragment
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="400dp"
    tools:context=".MapsActivity" />
Step 3. Then we need to declare the permissions related to the location and also need to check the permission at run time in devices above or equal to Android M
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    if (mContext.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && mContext.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MAP_PIN_LOCATION_REQUEST_CODE);
        return;
    }
}
Now obtain SupportMapFragment and get notified when the map is ready by overriding OnMapReadyCallback
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
Now let’s override the onMapReady function
@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));

    // Enable the zoom controls for the map
    mMap.getUiSettings().setZoomControlsEnabled(true);
}
googleMap.setOnMarkerDragListener(new GoogleMap.OnMarkerDragListener() {
    @Override
    public void onMarkerDragStart(Marker marker) {
    }

    @Override
    public void onMarkerDrag(Marker marker) {
    }

    @Override
    public void onMarkerDragEnd(Marker marker) {
        LatLng latLng = marker.getPosition();
        Geocoder geocoder = new Geocoder(getContext(), Locale.getDefault());
        try {
            android.location.Address address = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1).get(0);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
});

Picking location with map pin using Google maps in Android

No comments:

Post a Comment