Я следил за одной ссылкой, которая имеет код для создания карты, которую мы можем перетащить и получить текущее местоположение. Ссылка здесь. Как реализовать перетаскиваемую карту, например, uber android, Обновить с изменением местоположения
Я следил за всем кодом, но я не могу получить результат. Карта, которую мы можем перетащить, но не отображающая местоположение в текстовом режиме.
Может ли кто-нибудь помочь мне с этим?
ChooseFromMapLayout
<RelativeLayout
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" android:fitsSystemWindows="true"
tools:context="com.example.siddhi.go_jek.ChooseFromMapActivity"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
<fragment android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/map"
tools:context=".ChooseFromMapActivity"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_below="@+id/toolbar"
android:layout_alignParentStart="true" />
<LinearLayout
android:id="@+id/locationMarker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:orientation="vertical"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true">
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_place_black_48dp"
android:layout_gravity="center" />
</LinearLayout>
<LinearLayout
android:layout_width="280dp"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_gravity="center_horizontal"
android:layout_above="@+id/locationMarker"
android:layout_centerHorizontal="true"
android:layout_marginBottom="45dp">
<LinearLayout
android:layout_width="280dp"
android:layout_height="40dp"
android:background="@android:color/holo_blue_dark"
android:layout_gravity="center_vertical"
android:weightSum="1"
android:id="@+id/LinearLayoutUseLoc">
<TextView
android:layout_width="match_parent"
android:layout_height="20dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="@string/UseThisLoc"
android:id="@+id/textView23"
android:layout_gravity="center"
android:textAlignment="center"
android:layout_marginLeft="25dp"
android:drawableEnd="@drawable/ic_chevron_right_black_36dp"
android:textColorHighlight="@android:color/white"
android:textColor="@android:color/white" />
</LinearLayout>
<LinearLayout
android:layout_width="280dp"
android:layout_height="40dp"
android:background="@android:color/white"
android:layout_gravity="center_vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="@+id/textShowAddress"
android:layout_gravity="center"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="45dp"
android:background="@android:color/white"
android:orientation="horizontal"
android:layout_gravity="center_horizontal|top"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_below="@+id/toolbar"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:weightSum="1">
<EditText
android:layout_width="262dp"
android:layout_height="40dp"
android:layout_marginLeft="05dp"
android:layout_marginRight="05dp"
android:layout_weight="0.83" />
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:id="@+id/imageView22"
android:background="@drawable/ic_search_black_48dp" />
</LinearLayout>
</RelativeLayout>
ChooseFromMapActivity
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import com.example.siddhi.go_jek.R;
import com.example.siddhi.go_jek.GData;
import com.example.siddhi.go_jek.GPSTracker;
import com.example.siddhi.go_jek.AppLocationService;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnCameraChangeListener;
public class ChooseFromMapActivity extends AppCompatActivity implements
LocationListener, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private LocationRequest mLocationRequest;
GoogleMap mGoogleMap;
public static String ShopLat;
public static String ShopPlaceId;
public static String ShopLong;
private GoogleApiClient mGoogleApiClient;
boolean mUpdatesRequested = false;
private TextView markerText;
private LatLng center;
private LinearLayout markerLayout;
private Geocoder geocoder;
private List<Address> addresses;
private TextView Address;
double latitude;
double longitude;
private GPSTracker gps;
private LatLng curentpoint;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choose_from_map);
Address = (TextView) findViewById(R.id.textShowAddress);
markerLayout = (LinearLayout) findViewById(R.id.locationMarker);
markerText = (TextView) findViewById(R.id.locationMarkertext);
int status = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getBaseContext());
if (status != ConnectionResult.SUCCESS) {
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this,
requestCode);
dialog.show();
} else {
mLocationRequest = LocationRequest.create();
mLocationRequest.setInterval(GData.UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest
.setFastestInterval(GData.FAST_INTERVAL_CEILING_IN_MILLISECONDS);
mUpdatesRequested = false;
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.map)).getMap();
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
mGoogleMap.getUiSettings().setCompassEnabled(true);
mGoogleMap.getUiSettings().setRotateGesturesEnabled(true);
mGoogleMap.getUiSettings().setZoomGesturesEnabled(true);
PendingResult<Status> result = LocationServices.FusedLocationApi
.requestLocationUpdates(mGoogleApiClient, mLocationRequest,
new LocationListener() {
@Override
public void onLocationChanged(Location location) {
markerText.setText("Location received: "
+ location.toString());
}
});
Log.e("Reached", "here");
result.setResultCallback(new ResultCallback<Status>() {
@Override
public void onResult(Status status) {
if (status.isSuccess()) {
Log.e("Result", "success");
} else if (status.hasResolution()) {
try {
status.startResolutionForResult(ChooseFromMapActivity.this,
100);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
}
}
});
gps = new GPSTracker(this);
gps.canGetLocation();
latitude = gps.getLatitude();
longitude = gps.getLongitude();
curentpoint = new LatLng(latitude, longitude);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(curentpoint).zoom(19f).tilt(70).build();
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
mGoogleMap.clear();
mGoogleMap.setOnCameraChangeListener(new OnCameraChangeListener() {
@Override
public void onCameraChange(CameraPosition arg0) {
center = mGoogleMap.getCameraPosition().target;
markerText.setText(" Set your Location ");
mGoogleMap.clear();
markerLayout.setVisibility(View.VISIBLE);
try {
new GetLocationAsync(center.latitude, center.longitude)
.execute();
} catch (Exception e) {
}
}
});
markerLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
LatLng latLng1 = new LatLng(center.latitude,
center.longitude);
Marker m = mGoogleMap.addMarker(new MarkerOptions()
.position(latLng1)
.title(" Set your Location ")
.snippet("")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.ic_actionloc)));
m.setDraggable(true);
markerLayout.setVisibility(View.GONE);
} catch (Exception e) {
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onConnectionFailed(ConnectionResult arg0) {
}
@Override
public void onConnected(Bundle arg0) {
stupMap();
}
private class GetLocationAsync extends AsyncTask<String, Void, String> {
double x, y;
StringBuilder str;
public GetLocationAsync(double latitude, double longitude) {
x = latitude;
y = longitude;
}
@Override
protected void onPreExecute() {
Address.setText(" Getting location ");
}
@Override
protected String doInBackground(String... params) {
try {
geocoder = new Geocoder(ChooseFromMapActivity.this, Locale.ENGLISH);
addresses = geocoder.getFromLocation(x, y, 1);
str = new StringBuilder();
if (Geocoder.isPresent()) {
Address returnAddress = addresses.get(0);
String localityString = returnAddress.getLocality();
String city = returnAddress.getCountryName();
String region_code = returnAddress.getCountryCode();
String zipcode = returnAddress.getPostalCode();
str.append(localityString + "");
str.append(city + "" + region_code + "");
str.append(zipcode + "");
} else {
}
} catch (IOException e) {
Log.e("tag", e.getMessage());
}
return null;
}
@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 void onProgressUpdate(Void... values) {
}
}
@Override
public void onConnectionSuspended(int arg0) {
// TODO Auto-generated method stub
}
}
GPSTracker
public class GPSTracker extends Service implements LocationListener {
private final FragmentActivity mActivity;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location;
double latitude;
double longitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
protected LocationManager locationManager;
public GPSTracker(FragmentActivity activity) {
this.mActivity = activity;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mActivity
.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
} else {
this.canGetLocation = true;
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 (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",
"Impossible to connect to LocationManager", e);
}
return location;
}
public void updateGPSCoordinates() {
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
locationManager = null;
}
}
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
return longitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
public void showSettingsAlert() {
if (mActivity == null || mActivity.isFinishing()) {
return;
}
mActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
mActivity);
alertDialog.setTitle("GPS is settings");
alertDialog
.setMessage("Your GPS is disabled, Enable GPS in settings or continue with approximate location");
alertDialog.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mActivity.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog,
int which) {
}
});
alertDialog.create().show();
}
});
}
public List<Address> getGeocoderAddress(Context context) {
if (location != null) {
Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);
try {
List<Address> addresses = geocoder.getFromLocation(latitude,
longitude, 1);
return addresses;
} catch (IOException e) {
// e.printStackTrace();
Log.e("Error : Geocoder", "Impossible to connect to Geocoder",
e);
}
}
return null;
}
public String getAddressLine(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String addressLine = address.getAddressLine(0);
return addressLine;
} else {
return null;
}
}
public String getLocality(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String locality = address.getLocality();
return locality;
} else {
return null;
}
}
public String getPostalCode(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String postalCode = address.getPostalCode();
return postalCode;
} else {
return null;
}
}
public String getCountryName(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String countryName = address.getCountryName();
return countryName;
} else {
return null;
}
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onProviderDisabled(String provider) {
showSettingsAlert();
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
This below code and functions are showing in gray, not getting used.
import com.example.siddhi.go_jek.R;
import com.example.siddhi.go_jek.GData;
import com.example.siddhi.go_jek.GPSTracker;
public static String ShopLat;
public static String ShopPlaceId;
public static String ShopLong;
public String getAddressLine(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String addressLine = address.getAddressLine(0);
return addressLine;
} else {
return null;
}
}
public String getLocality(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String locality = address.getLocality();
return locality;
} else {
return null;
}
}
public String getPostalCode(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String postalCode = address.getPostalCode();
return postalCode;
} else {
return null;
}
}
public String getCountryName(Context context) {
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
String countryName = address.getCountryName();
return countryName;
} else {
return null;
}
}