Development issue/problem:

How to implement a card through drag and drop, such as. B. Uber? I use Google Maps v2. I actually got the solution by redirecting this job and sharing my full solution here.

How can I solve this problem?

Solution 1:

The update with the last code also includes the change of location with automatic filling.

You can find the complete project here

The logic is simple – we need a wire and we add a map and a marker in that wire, then we make a gravity layout in the middle and get the latitude and longitude of the center of the map on the camera – change
See this answer
here is my code
make active_maps.xml

TextView background sound xml create rounded_corner_folder.xml here

and this is my MainActivity.java.

Package com.sample.sishin.maplocation ;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.intention;
import android.content.pm.PackageManager;
import android.location.Location.Location;
import android.os.Handler;
import android.os.ResultReceiver;
import android.provider.Settings;
import android.support.v4.app.ActivityCompatible;
import android.os.Bundle ;

import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast ;

import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GoogleApiAvailability; import com.google.android.gms.common.GooglePlayServicesNotAvailableException; import com.google.android.gms.common.GooglePlayServicesRepayableException; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.Status; import com.google.android.gms.locationRequest; import com.google.android.gms.locationServices; import com.google.android.gms.location.places; import com.google.android.gms.locations.ui.PlaceAutocomplet; 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.CameraPosition; import com.google.android.gms.maps.model.LatLng ;

The public class of MapsActivity extends the AppCompatActivity application with OnMapReadyCallback, GoogleApiClient.ConnectionCallback, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {
private GoogleMap mMap;
private GoogleApiClient mGoogleApiClient;
private final static in PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
private static in String TAG = MAP LOCATION;
Context mContext;
TextView mLocationMarkerText;
private LatLng mCenterLatLong ;

/**
* Recipient registered in this activity to receive a response from the Address Search Service.
*/
private addressResult Receiver mResult Receiver;
/**
* Formatted location address.
*/
protected String mAddressOutput;
protected String mAreaOutput;
protected String mCityOutput;
protected String mStateOutput;
EditText mLocationAddress;
TextView mLocationText;
private static final int REQUEST_CODE_AUTOCOMPLETE = 1;
Toolbar ;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
mContext = this;
// Get SupportMapFragment and receive a notification when the card is ready to use.
SupportMapFragment folderFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map) ;

mLocationMarkerText = (TextView) findViewById(R.id.locationMarkertext);
mLocationAddress = (EditText) findViewById(R.id.Address);
mLocationText = (TextView) findViewById(R.)).id.Locality);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true) ;

getSupportActionBar().setTitle(getResources().getString(R.string.app_name)) ;

mLocationText.setOnClickListener(new View.OnClickListener() {
@Override
public null and void onClick(View view)) {

openAutocompleteActivity() ;

}

);
mapFragment.getMapAsync(this);
mResultReceiver = new AddressResultReceiver(new Handler();)

as (checkPlayServices()) {
// If this check is successful, continue normal processing.
// Otherwise, ask the user for a valid MOT for the game services.
if (! AppUtils.isLocationEnabled(mContext)) {
// Inform user
AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
dialog.setMessage(Location not enabled!);
dialog.setPositiveButton(Open Location Settings, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
Intent myIntent = new Intent(Settings).ACTION_LOCATION_SOURCE_SETTINGS)));
startActivity(myIntent);
}
})));
dialog.setNegativeButton(Cancel, new DialogInterface.OnClickListener() {

@Override
public blank onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO auto-generation method stub

});
dialog.show();
}
buildGoogleApiClient();
} otherwise {
Toast.makeText(mContext, Location not supported in this device, Toast.LENGTH_SHORT).show();
}

}

/**
* Handle the card as soon as it is available.
* This reminder is activated when the card is ready for use.
* Here we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services are not installed on the device, the user will be prompted to install
* in the SupportMapFragment. This method will only be activated after user
* Google Play services is installed and returned to the application.
*/
@ Get
public void onMapReady(GoogleMap googleMap) {
Log.d(TAG, OnMapReady);
mMap = googleMap ;

mMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {@CameraChange(CameraPositionCameraPosition) {Log.d(CameraPosition + , cameraPosition + );mCenterLatLong = cameraPosition.target ;

mMap.clear() ;

Try

Location mLocation = new Location();
mLocation.setLatLatitude(mCenterLatLong.latitude);
mLocation.setLongitude(mCenterLatLong.longitude) ;

startIntentService(mLlocation) ;
mLocationMarkerText.setText(Lat : + mCenterLatLong.latitude + , + Long : + mCenterLatLong.longitude) ;

} catch (Exception e) {
e.printStackTrace();
}
}
});
if (ActivityCompatible.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.GRANTED_PERMISSION && ActivityCompatible.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.GRANTED_PERMISSION) {
// TODO : Consider calling
// ActivityCompatible#requestPermissions
// here to request the missing permissions, and then handling
// public void onRequestPermissionsResult (int requestCode, String[] permissions,
// int[] grantResults)
// in the event the user grants permission. See documentation
// ActivityCompat#requestPermissions for more details.
return;
}
// mMap.setMyLocationEnabled(true);
// mMap.setMyLocationButtonEnabled(true);
//
// // Add marker to Sydney and move camera
// LatLng sydney = new LatLng(-34, 151);
// mMap.addMarker (new MarkerOptions().position(sydney).title(marker in Sydney));
// mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}

@Override
public void onConnected(Bundle bundle) {
if (ActivityCompatible.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)) != PackageManager.WARRANTY_PERMISSION && ActivityCompatible.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.WARRANTY_PERMISSION) {
// TODO : Consider calling
// ActivityCompatible#requestPermissions
// here to request the missing permissions, and then handling
// public void onRequestPermissionsResult (int requestCode, String[] permissions,
// int[] grantResults)
// in the event the user grants permission. See Document
for more information // about ActivityCompatible#requestPermissions.
return;
}
Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
changeMap(mLastLocation);
Log.d(TAG, ON connected) ;

} else try
{
LocationServices.FusedLocationApi.removeLocationUpdates (
mGoogleApiClient, this) ;

} capture (exception e) {
e.printStackTrace();
}
try {
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000);
mLocationRequest.setFastInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this) ;

} capture (exception e) {e.printStackTrace();} capture (exception e) {e.printStackTrace()

}

@Override
public void onConnectionSuspended(int i) {
Log.i(TAG, suspended connection);
mGoogleApiClient.connect();
}

@Override
public invalid onLocationChanged(Location location) {
try {
as (location != invalid)
changeMap(location);
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this) ;

} capture (exception e) {
e.printStackTrace();
}
}

@Override
public null and void onConnectionFailed (ConnectionResult connectionResult) {

}

protected synchronized null buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build() ;
}

@Override
protected void onStart() {
super.onStart() ;
try {
mGoogleApiClient.connect() ;

} capture (exception e) {
e.printStackTrace();
}
}

@Override
protected void onStop() {
super.onStop();
try {

} catch (RuntimeException e) {e.printStackTrace();}as (mGoogleApiClient!)= null && mGoogleApiClient.isConnected()) {mGoogleApiClient.disconnect();}}

private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUerRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
PLAY_SERVICES_RESOLUTION_REQUEST).show();
} otherwise {
//finish();
}
return false;
}
return true;
}

private void changeMap(Location) {

Log.d(TAG, Accessibility Map + mMap) ;

if (ActivityCompatible.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION.PERMISSION_GRANTED && ActivityCompatible.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO : Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then handling
// public void onRequestPermissionsResult (int requestCode, String[] permissions,
// int[] grantResults)
// when the user grants permission. See Document
for more information // about ActivityCompatible#requestPermissions.
back;
}

// Check whether or not the card has been successfully created
as (mMap != null) {
mMap.tUiSettings().setZoomControlsEnabled(false) ;
LatLng ;

latLong = new LatLng(location.getLatitude(), location.getLongitude() ;

CameraPosition CameraPosition = new CameraPosition.Builder()
.target(latLong).zoom(19f).tilt(70).build() ;

mMap.setMyLocationEnabled(true) ;
mMap.setMyLocationButtonEnabled(true) ;
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition))

mLocationMarkerText.setText(Lat: + location.getLatitude() + , + Long: + location.getLongitude()) ;
startIntentService(location) ;

} otherwise {
Toast.makeText(getApplicationContext(),
Sorry, no cards created, Toast.LENGTH_SHORT)
.show();
}

}

/**
* Recipient of the data sent by FetchAddressIntentService.
*/
class AddressResultReceiver extends ResultReceiver {
public AddressResultReceiver(handler) {
super(handler);
}

/**
* Receives the data sent by the FetchAddressIntentService and updates the user interface in MainActivity.
*/
@Delete
protected void onCatch result (int resultCode, Bundle resultData) {

// Displays the address string or error message sent by the Setup Service.
mAddressOutput = resultData.getString(AppUtils.LocationConstants.RESULT_DATA_KEY) ;

mAreaOutput = resultData.getString(AppUtils.LocationConstants.LOCATION_DATA_AREA) ;

mCityOutput = resultData.getString(AppUtils.LocationConstants.LOCATION_DATA_CITY) ;
mStateOutput = resultData.getString(AppUtils.LocationConstants.LOCATION_DATA_STREET) ;

displayAddressOutput() ;

// Display a toast message when the address is found.
if (resultCode == AppUtils.LocationConstants.SUCCESS_RESULT) {
// showToast(getString(R.string.address_found)) ;

}

}

}

/**
* Update the address in the interface.
*/
protected void displayAddressOutput() {
// mLocationAddressTextView.setText(mAddressOutput);
try {
as (mAreaOutput != null)
// mLocationText.setText(mAreaOutput+ )

mLocationAddress.setText(mAddressOutput);
//mLocationText.setText(mAreaOutput);
} catch (Exception e) {
e.printStackTrace();
}
}.

/*** Creates an intention, adds location information as additional data and launches the intention service to retrieve the address*. */protected empty startIntentService(Location mLocation) {// Creates an intention that is forwarded to the intention service responsible for receiving the address.
Intention = new intention (this one, FetchAddressIntentService.class) ;

// Make the recipient of the result look like an addition to the service.
intention.putExtra(AppUtils.LocationConstants.RECEIVER, mResultReceiver) ;

// Provide location information as additional information for the service.
int.putExtra(AppUtils.LocationConstants.LOCATION_DATA_EXTRA, mLocation) ;

//Start maintenance. If the service is not running yet, it is initiated and launched
// (a process can be created for it); if it is running, it continues to run. The
// service ends automatically after all intentions have been processed.
startService (intention);
}

private void openAutocompleteActivity() {
try {
// The autocompletion process requires the availability of the Google Play service. Intent
// The manufacturer checks it and throws an exception if this is not the case.
Intent = new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_FULLSCREEN)
.build(this);
startActivityForResult(intent, REQUEST_CODE_AUTOCOMPLETE);
} catch (GooglePlayServicesRepayableException e) {
// Indicates that Google Play Services is not installed or is not up to date.
// Ask the user to solve problems.
GoogleApiAvailability.getInstance().getErrorDialog(this, e.getConnectionStatusCode(),
0 /* requestCode */).show();
} catch (GooglePlayServicesNotAvailableException e) {
// Indicates that the Google Play services are not available and that the problem is not easily resolved
//.
Message String = Google Play services are not available: +
GoogleApiAvailability.getInstance().getErrorString(e.errorCode) ;

Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
}
}

/**
* Called after the autocompletion activity to return the result.
*/
@Override
public void onActivityResult(int requestCode, resultCode, intent data) {
super.onActivityResult(requestCode, resultCode, data) ;

// Make sure that the result is retrieved from the autofill widget.
if (requestCode == REQUEST_CODE_AUTOCOMPLETE) {
if (resultCode == RESULT_OK) {
// Remove the user-selected location from the intention.
Place = PlaceAutocomplete.getPlace(mContext, data) ;

// Filter based on the location of the TODO call

LatLng latLong ;

latLong = place.getLatLng() ;

//mLocationText.setText(place.getName() + ) ;

CameraPosition CameraPosition = new CameraPosition.Builder()
.target(latLong).zoom(19f).tilt(70).build() ;

if (ActivityCompatible.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION.PERMISSION_GRANTED && ActivityCompatible.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO : Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then handling
// public void onRequestPermissionsResult (int requestCode, String[] permissions,
// int[] grantResults)
// when the user grants permission. See Document
for more information // about ActivityCompatible#requestPermissions.
return;
}
mMap.setMyLocationEnabled(true);
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition)) ;

}

} different if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
Status = PlaceAutocomplete.getStatus(mContext, data);
} different if (resultCode == RESULT_CANCELED) {
// Indicates that the activity was closed for selection. For example, if
// the user has pressed the return key.
}
}

}

And the manifest file

Give here a description of the image

Solution 2:

Because LocationClient doesn’t work, I used GoogleApiClient, here is the code for everyone who wants to implement it.
Simply replacing LocationClient with GoogleApiClient is identical to the code in @Sishin.

Import java.io.IOException;
Import java.util.List;
Import java.util.Local ;

import android.app.dialog;
import android.content.IntentSender.SendIntentException;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.AsyncTask;
import android.os.AsyncTask.os.bundle;
import android.support.v7.app.App.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView ;

import com.app.anycabs.R.; com.app.common.GPSTracker; com.app.modle.GData.import; com.google.android.gms.common.ConnectionResult; com.google.android.gms.common.GooglePlayServicesUtil; com.google.android.gms.common.api.GoogleApiClient.import; com import.google.android.gms.common.api.PendingResult;import com.google.android.gms.common.api.ResultCallback;import com.google.android.gms.common.api.Status;import com.google.android.gms.location.LocationListener;import com.google.android.gms.location.LocationRequest;com.google.android.gms.location.locationServices; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.GoogleMap.OnCameraChangeListener; import com.google.android.gms.maps.MapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory;import com.google.android.gms.maps.model.CameraPosition;import com.google.android.gms.maps.model.LatLng;import com.google.android.gms.maps.model.Marker;import com.google.android.gms.maps.model.MarkerOptions ;

The MainActivity public class extends AppCompatActivity with
LocationListener, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
// Location Services Connection Request
private LocationRequest mLocationRequest;
GoogleMap mGoogleMap ;

public static String ShopLat;
public static String ShopPlaceId;
public static String ShopLong;
// Saves the current location client instance in this object
private GoogleApiClient mGoogleApiClient;
boolean mUpdatesRequested = false ;
private TextView markerText;
private LatLng center;
private LinearLayout markerLayout;
private geocoder geocoder;
private list addresses;
private TextView address;
double latitude;
double longitude;
private GPSTracker gps;
private LatLng curent ;

@Overview
protected void onCreate(StoredInstanceState bundle) {
super.onCreate(storedInstanceState);
setContentView(R.layout.activity_curent_locations);
markerText = (TextView) findViewById(R.id.locationMarkertext);
Address = (TextView) findViewById(R.).id.addressText);
markerLayout = (LinearLayout) findViewById(R.id.locationMarkertext);
// Get Google Play availability status
int status = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getBaseContext()) ;

if (status != Connection result.SUCCESS) { // Google Play service
// not available

int requestCode = 10;
Dialog = GooglePlayServicesUtil.getErrorDialog(status, this,
requestCode);
dialog.show() ;

} otherwise there are { // Google Play services available.

// Get the reference SupportMapFragment
// Create a new global location parameter object
mLocationRequest = LocationRequest.create() ;

/*
* Set update interval
*/
mLocationRequest.setInterval(GData.UPDATE_INTERVAL_IN_MILLISECONDS) ;

// Use high precision
mLL Location Request
.setPriority(Location Request.HIGH_ACCURACY_PRIORITY) ;

// Set the interval limit to one minute
mLocationRequest
.setFastInterval(GData.FAST_INTERVAL_CEILING_IN_MILLISECONDS) ;

// Note that localization updates are disabled until the user activates them at
mUpdatesRequested = false ;

/*
* Create a new location client that uses the enclosure class to process
* recalls.
*/
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build() ;

mGoogleApiClient.connect();
}
}

private void stupMap() {
try {

mGoogleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.curentlocationmapfragment)).getMap() ;

// Enable MyLocation in Google Map
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.getUiSettings().setZoomControlsEnabled(false);
mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
mGoogleMap.getUiSettings().setCompassEnabled(true);
mGoogleMap.getUiSettings().setRotateGesturesEnabled(true);
mGoogleMap.getUiSettings().setZoomGesturesEnabled(true) ;

Pending the result = LocationServices.FusedLocationApi
.requestLocationUpdates(mGoogleApiClient, mLocationRequest,
new LocationListener() {)

@General invalid
onLocationChanged(Location) {
markerText.setText(Location received:
+ location.toString() ;

}
});

Log.e (Reached, here) ;

result.setResultCallback(new ResultCallback() {)

@Override
public void on Result (Status) {.

if (status.isSuccessful()) {

Log.e (result, success) ;

} other as (status.hasResolution()) {
// Google offers a way to solve the problem
try {
status.startResolutionForResult(MainActivity.this,
100);
} catch (SendIntentException e) {
e.printStackTrace();
}
}
}
});
gps = new GPSTracker(this) ;

gps.canGetLocation() ;

latitude = gps.getLatitude() ;
longitude = gps.getLongitude() ;
pour point = new LatLng(latitude, longitude) ;

CameraPosition CameraPosition = new CameraPosition.Builder()
.target(curentpoint).zoom(19f).tilt(70).build() ;

mGoogleMap.setMyLocationEnabled(true) ;
mGoogleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition)) ;
// Erase all existing markers
mGoogleMap.clear() ;

mGoogleMap.setOnCameraChangeListener(new OnCameraChangeListener() {)

@Override
public blank onCameraChange (CameraPosition arg0) {
// TODO Automatically generated method stub
center = mGoogleMap.getCameraPosition().target ;

markerText.setText( Set your location ) ;
mGoogleMap.clear() ;
markerLayout.setVisibility(View.VISIBLE) ;

try {
new GetLocationAsync(center.latitude, center.longitude)
.execute() ;

Capture (exception e) {
}
}
}) ;

markerLayout.setOnClickListener(new OnClickListener() {)

@Overview
public blank onClick(View v) {
// TODO Automatically generated heel method

Try

LatLng latLng1 = new LatLng (central latitude, central longitude) ;

Marker m = mGoogleMap.addMarker(new MarkerOptions()
.position(latLng1)
.title( Set your location)
.snippet()
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.pin_last)))) ;
m.setDraggable(true) ;

markerLayout.setVisibility(View.GONE);
} capture (Exception e) {
}

}
});

} capture (exception e) {
e.printStackTrace();
}
}

@Override
public void onLocationChanged(Location) {
// TODO Automatically generated method heel

}

@Override
public void onConnectionFailed (ConnectionResult arg0) {
// TODO Automatically generated method loop

}

@Override
public void onConnected(Bundle arg0) {
// TODO auto-generation method stub
stupMap() ;

}

The GetLocationAsync private class expands AsyncTask {

// logical duplicateResponse;
double x, y;
StringBuilder str ;

public GetLocationAsync (double latitude, double longitude) {
// TODO Stub of constructor automatically generated

x = latitude;
y = longitude;
}

@Override
protected void onPreExecute() {
Address.setText( Getting location );
}

@Override
protected String doInBackground(String… params) {

try {
geocoder = new Geocoder(MainActivity.this, Locale.ENGLISH) ;
addresses = geocoder.getFromLocation(x, y, 1) ;
str = new StringBuilder() ;
as (Geocoder.isPresent()) {
address returnAddress = addresses.get(0) ;

String localityString = returnAddress.getLocality() ;
String city = returnAddress.getCountryName() ;
String region_code = returnAddress.getCountryCode() ;
String postcode = returnAddress.getPostalCode() ;

str.append(localityString + ) ;
str.append(city + + + + region_code + ) ;
str.append(postcode + ) ;

Otherwise {
}
} catch (IOException e) {
Log.e(tag, e.getMessage());
}
return zero ;

}

@Override
protected void onPostExecute(String Result) {
try {
Address.setText(addresses.get(0).getAddressLine(0)
+ addresses.get(0).getAddressLine(1) + );
} catch (Exception e) {
e.printStackTrace();
}
}.

Override
protected blank onProgressUpdate(Void… values) {

}
}

@Override
public void onConnectionSuspended(int arg0) {
// TODO Automatically generated tips method

}

}

Where GPSTracker as shown below :

The GPSTracker public class extends the implementations of the LocationListener service {

private endpoint fragmentActivity mActivity ;

// Flag for GPS status
Boolean isGPSEnabled = false ;

// Flag for network status
Boolean isNetworkEnabled = false ;

boolean canGetLocation = false ;

Location; double latitude
; double longitude
;

// Minimum distance to change updates for counters
private static end long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10
// Counters

// Minimum network time in milliseconds
Long static private time MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 min.

// Declaration of protected LocationManager
LocationManager ;

public GPSTracker (FragmentActivity) {
this.mActivity = activity;
getLocation();
}

public GetLocation() {
try {
locationManager = (LocationManager) mActivity
.getSystemService(LOCATION_SERVICE) ;

// Obtain GPS Status
isGPSEnabled = LocationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER) ;

// Obtain network status
isNetworkEnabled = LocationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER) ;

if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider enabled
} else {
this.canGetLocation = where ;

// First obtain the location from network provider
, if (isNetworkEnabled) {
locationManager.requestLocationUpdates (
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this) ;

if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
updateGPSCoordinates();
}
}
// if GPS is enabled, receive late/long coordinates via GPS services
if (isGPSEnabled) {
if (location ==null) {
locationManager.requestLocationUpdates (
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this) ;

if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
updateGPSCoordinates();
}
}
}
}
} catch (Exception e) {
// e.printStackTrace();
Log.e(Error: Location,
Cannot connect to LocationManager, e);
}.

place of return;
}

public invalid updateGPSCoordinates() {
if (location != invalid) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}

/**
* Stop using the GPS receiver By calling up this function, you stop using the GPS in your
* app
*/.

public invalid stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
locationManager = null;
}
}.

/**
* Функция получения получения широты
*/
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}.

обратная широта ;
}

/**
* Функция получения долготы
*/
public double getLongitude() {
as (location != null) {
longitude = location.getLongitude();
}

Return length;
}

/**
* GPS/Wifi check function enabled
*/
public boolean canGetLocation() {
returns this.canGetLocation;
}

/**
* Function for displaying the parameter warning dialog
*/
public void showSettingsAlert() {

if (mActivity == null | mActivity.isFinishing()) {
back;
}

mActivity.runOnUiThread(new Runnable()) {

@Override
public void run() {

AlertDialog.Builder alertDialog.Builder = new AlertDialog.Builder(
mActivity) ;

// Set the title of the
alertDialog.setTitle dialog box (GPS is the setting) ;

// setDialog
WarningDialog
.setMessage (Your GPS is switched off, enable GPS in the settings or continue with the estimated position) ;

//
alertDialog.setPositiveButton(Settings,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int who) {
intent = new intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mActivity.startActivity(intent);
}
})

// when the cancel button is pressed, setNegative button (Cancel, new DialogInterface.OnClickListener() { public emptyClick(last DialogInterface dialog, int who) { last DialogInterface, int)

// UserSerch doSerch = new UserSerch();
// doSerch.doserchOn();
// dialog.cancel();
}
})

// show message
alertDialog.create().show();
}
}) ;

}

/**
* receive list of addresses by latitude and longitude
*
* @return null or list
*/
public list getGeocoderAddress(Context context) {
if (location != null) {
geocoder geocoder = new Geocoder(context, Local).ENGLISH);
try {
List addresses = geocoder.getFromLocation(latitude,
longitude, 1);
} catch (IOException e) {
// e.printStackTrace();
Log.e(Error: Geocoder, Cannot connect to Geocoder,
e);
}
}
}

renvoie zéro ;
}

/**
* Essayez d’obtenir AddressLine
*
* @return null ou addressLine
*/
public String getAddressLine(Context context) {
List addresses = getGeocoderAddress(context) ;
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0) ;
String addressLine = address.getAddressLine(0) ;

return addressLine ;
} else {
return null ;
}
}

/**
* Tentative d’obtention de la localisation
*
* @return null or locality
*/
public String getLocality(Context context) {
List addresses = getGeocoderAddress(context) ;
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0) ;
String locality = address.getLocality() ;

lieu de retour ;
} sinon {
renvoie zéro ;
}
}

/**
* Tentative d’obtention du code postal
*
* @return null ou postalCode
*/
public String getPostalCode(Context context) {
List addresses = getGeocoderAddress(context) ;
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0) ;
String postalCode = address.getPostalCode() ;

return postal code;
} otherwise {
return nil;
}
}.

/**
* Attempt to obtain the country name
*
* @return null or postalCode
*/
Public string getCountryName(Context context) {
Address list = getGeocoderAddress(context) ;
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0) ;
CountryName string = address.getCountryName() ;

returns countryName country;
} otherwise {
returns zero;
}
}.

@Override
public invalidity onLocationChanged(Location) {
}

@Override
public null and void onProviderDisabled(String provider) {
showSettingsAlert();
}

@Override
public null and void onProviderEnabled(String Provider) {
}.

@Override
public null and void onStatusChanged(String provider, int status, Bundle extras) {
}

@Override
public IBinder onBind(Intent) {
return null;
}
}

I hope that helps somebody.
Image

Solution 3:

You can try this example on my….. Give it a try.

An example I made

Active_main.xml

marker_view.xml

Location_Display_View.xml

MapWrapperLayout.java

Package com.rajeshvijayakumar.map.demo.wrapper ;

The MapWrapperLayout public class expands FrameLayout {

OnDragListener public interface {
public void onDrag(MotionEvent motionEvent);
}

private mOnDragListener ;

public MapWrapperLayout(Context) {
super(context);
}

@Check
public boolean sendTouchEvent(MotionEvent ev) {
if (mOnDragListener != null) {
mOnDragListener.onDrag(ev);
}
return super.dispatchTouchEvent(ev);
}

public void setOnDragListener(OnDragListener mOnDragListener) {
this.mOnDragListener = mOnDragListener;
}
}

CustomMapFragment.java

Package com.rajeshvijayakumar.map.demo.ui ;

the CustomMapFragment public class expands MapFragment {

private viewing mOriginalView ;
private MapWrapperLayout mMapWrapperLayout ;

General image
onCreateView (inflatable air inlet, ViewGroup container, contents of the stored container) {
mOriginal image = super.onCreateView (inflatable air inlet, container, contents of the stored container) ;

mMapWrapperLayout = new MapWrapperLayout(getActivity()) ;
mMapWrapperLayout.addView(mOriginalView) ;

reverse mMapWrapperLayout;
}

@Override
public view getView() {
return mOriginalView;
}

public invalid setOnDragListener(MapWrapperLayout.OnDragListener) {
mMapWrapperLayout.setOnDragListener;
}
}

MainActive.java

the MainActivity public class expands the OnDragListener activity {

// Google Map
Private GoogleMap googleMap;
Private CustomMapFragment ;

private View mMarkerParentView;
private ImageView mMarkerImageView ;

private int imageParentWidth = -1 ;
private int imageParentHeight = -1 ;
private int imageHeight = -1 ;
private int centerX = -1 ;
private int centerY = -1 ;

Private TextView mLocationTextView ;

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

// initializeUI
initializeUI() ;

}

private void initializeUI() {

try {
// Load
initilizeMap() ;

} catch (Exception e) {
e.printStackTrace();
}
mLocationTextView = (TextView) findViewById(R.id.)location_text_view);
mMarkerParentView = findViewById(R.id.marker_view_incl);
mMarkerImageView = (ImageView) findViewById(R.id.marker_icon_view);
}.

@
public void handling onWindowFocusChanged(boolean hasFocus) {
DisplayMetrics displaymetrics = new DisplayMetrics() ;
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics) ;

imageParentWidth = mMarkerParentView.getWidth() ;
imageParentHeight = mMarkerParentView.getHeight() ;
imageHeight = mMarkerImageView.getHeight() ;

centerX = imageParentHeight / 2;
centerY = (imageParentHeight / 2) + (imageHeight / 2);
}

private void initilizeMap() { submit (googleMap ==zero) {mCustomMapFragment = ((CustomMapFragment) getFragmentManager().findFragmentById(R.id.map));mCustomMapFragment.setOnDragListener(MainActivity.this);googleMap = mCustomMapFragment.getMap();// check for successful map creationals (googleMap == null) {Toast.makeText(getApplicationContext(),Sorry! no maps created, Toast.LENGTH_SHORT).show();}// CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng,// 10);// googleMap.animateCamera(cameraUpdate);// locationManager.removeUpdates(this);}

@Override
protected void onResume() {
super.onResume();
}

@Overrid public void onDrag(MotionEvent motionEvent) {if (motionEvent.getAction() == MotionEvent.ACTION_UP) {Projection projection = (googleMap != null && googleMap.getProjection() != null) ? googleMap.getProjection(): null ;//als (projection != null) {LatLng centerLatLng = projection.fromScreenLocation(new Point(centerX, centerY))) ;updateLocation(centerLatLng) ;}}}

private void updateLocation(LatLng centerLatLng) {
if (centerLatLng != null) {
Geocoder geocoder = new Geocoder(MainActivity.this,
Locale.getDefault() ;

List addresses = new ArrayList();
try {
addresses = geocoder.getFromLocation(centerLatLng.latitude,
centerLatLng.longitude, 1);
} catch (IOException e) {
e.printStackTrace();
}

if (Addresses != null && Addresses.Size() > 0) {

String addressIndex0 = (addresses.get(0).getAddressLine(0) != null) ? addresses
.get(0).getAddressLine(0): null;
String addressIndex1 = (addresses.get(0).getAddressLine(1) != null) ? addresses
.get(0).getAddressLine(1) : null;
String addressIndex2 = (addresses.get(0).getAddressLine(2) != null) ? addresses
.get(0).getAddressLine(2) : null;
String addressIndex3 = (addresses.get(0).getAddressLine(3) != null) ? addresses
.get(0).getAddressLine(3) : null ;

String completeAddress = addressIndex0 + , + addressIndex1 ;

if (addressIndex2 != null) {completAddress += , + addressIndex2;}if (addressIndex3 != null) {completAddress += , + addressIndex3;} if (completeAddress != null) {mLocationTextView.setText(completeAddress);}}}}}

Solution 4:

GPS Class by #Shvet year.

The CarSelectActivity public class extends the activity base to include GoogleApiClient.OnConnectionFailedListener, LocationListener, OnMapReadyCallback, GoogleApiClient.ConnectionCallback {

private GoogleApiClient mGoogleApiClient;
private static final LatLngBounds BOUNDS_GREATER_SYDNEY = new LatLngBounds(
new LatLng(-34.041458, 150.)790100), new LatLng(-33.682247, 151.383362);
private GoogleMap mGoogleMap;
private ImageView mMarkerImageView;
private GPSTracker gps ;

@Override
protected void onCreate(@Nullable final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
setContentView(R.layout.activit_carselect;)

final SupportMapFragment folderFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
inilizviews();
}

private void inilizviews() {
gps = new GPSTracker(this);
mMarkerImageView = (ImageView) findViewById(R.id.im_marker);
}

@Override
public void onConnectionChanged(@NotCompleted final connectionOpen connectionResult) {
}
@Override
public void onLocationChanged(final location) {
}.

@Override
public void onMapReady(final GoogleMap googleMap) {
mGoogleMap = googleMap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mGoogleMap.isMyLocationButtonEnabled();
mGoogleMap.isZoomControlsEnabled().isZoomControlsEnabled();
mGoogleMap.setMyLocationButtonEnabled(true);
}.

@Checking public void
onConnected(@Checking final package) {
mGoogleApiClient.connect();
setUpDragListners();
}

@Override
public void onConnectionSuspended(int i) {
}
private void setUpDragListners() {

if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompatible.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
gps.canGetLocation();
LatLng curentpoint = new LatLng(gps.getLatitude(), gps.getLongitude());
CameraPosition CameraPosition = new CameraPosition.Builder()
.target(curentpoint).zoom(15f).tilt(30).build();
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition);
mGoogleMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
@General
public void onCameraChange(CameraPosition arg0) {
// TODO auto-generation method stub
LatLng center = mGoogleMap.getCameraPosition().target ;
try {
getLocation(center).latitude, center.longitude);
} capture (last exception e) {
e.printStackTrace();
}
}
});
private empty getLocation(double latitude, double longitude) {
Geocoder geocoder = new geocoder(CarSelectActivity.this, Locale.ENGLISH);
address = geocoder.getFromLocation(latitude, longitude, 1)

textView_places.setText(addresses.get(0).getAddressLine(0)
+ addresses.get(0).getAddressLine(1) + );
}
}

Solution No 5:

Kotlin link:
Xml packaging with relative division :

fun mapInit(googleMap : GoogleMap){
googleMap.apply {
// just any location our map points to at startup
val klcc = LatLng(3.1579513, 101.7116233)
addMarker(MarkerOptions().apply {
position(klcc)
title(MarkerOptions to klcc)
drag(false)
})
// Install zoom level
animateCamera(CameraUpdateFactory.newLatLngZoom(klcc,18f))

// specifies the events to respond to
setOnCameraMoveListener([protected via email])
setOnCameraIdleListener([protected via email])

}
}

override fun onCameraMove() {mMap.clear()// show imageViewimgPinUp?.visibility = View.VISIBLE} override fun onCameraIdle() {// hide imageViewimgPinUp?.visibility = View.GONE// Configure the map marker with a configurable icon/// and place it at the current position of the camera on the mapMarkerOptions = MarkerOptions().position(mMap.cameraPosition.target).icon(BitmapDescriptorFactory.fromResource(R.drawable.location_pin))mMap.addMarker(markerOptions)

}

Good luck!

You May Also Like

How to remove Anatova ransomware from Windows 10 PCs

You can use the Windows Safe Mode to stop the Anatova ransom…

Security Measures to Minimize E-Commerce Security Threats in 2021

One of the most important things to do when purchasing online is…

How to Choose the Optimal Aesthetic Clinic Management Software?

The choice of clinic management software is vast these days, but how…

Fix DPC Watchdog Violation error in Windows 10

How do I correct errors related to the RPC-VIOLATION? 1. Check your…