Step 1. import libary in build.gradle
implementation 'com.google.android.gms:play-services-maps:17.0.0'Step 2. creata a layout
implementation 'com.google.android.gms:play-services-location:17.0.0'
<fragmentStep 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
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="400dp"
tools:context=".MapsActivity" />
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {Now obtain SupportMapFragment and get notified when the map is ready by overriding OnMapReadyCallback
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;
}
}
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);Now let’s override the onMapReady function
mapFragment.getMapAsync(this);
@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();
}
}
});
No comments:
Post a Comment