Android studio 如何修复标记、移动地图和更新位置
我做了一个显示当前位置的活动,并在我拖动标记时更新位置,但我需要做一个自定义标记,该标记应固定在中心,并且每当我移动地图时,它应在textview中更新位置。我现在使用内置标记,所以不需要指定布局。这是我的密码:Android studio 如何修复标记、移动地图和更新位置,android-studio,google-maps,Android Studio,Google Maps,我做了一个显示当前位置的活动,并在我拖动标记时更新位置,但我需要做一个自定义标记,该标记应固定在中心,并且每当我移动地图时,它应在textview中更新位置。我现在使用内置标记,所以不需要指定布局。这是我的密码: import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.app.ActivityCompat; import androidx.fragment.app.
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.FragmentActivity;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.PorterDuff;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.internal.GoogleApiAvailabilityCache;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import 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.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.UiSettings;
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;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FieldValue;
import com.google.firebase.firestore.FirebaseFirestore;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionDeniedResponse;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.single.PermissionListener;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
public class currentLocationMapActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener, BottomSheetDialog.BottomSheetListener, GoogleMap.OnMarkerDragListener {
private GoogleMap mMap;
private GoogleApiClient mGoogleApiClient;
private Location mLocation;
private LocationRequest mLocationRequest;
private com.google.android.gms.location.LocationListener locationListener;
private long UPDATE_INTERVAL = 55000;
private long FASTEST_INTERVAL = 50000;
private LocationManager locationManager;
private MarkerOptions markerOptions;
private Marker marker;
private LatLng latLng, latlng1;
private boolean isPermission;
private View mapView;
private ImageView backbtn;
public TextView changebutton;
private TextView cityTextView, AddressTextView;
public RelativeLayout relativeLayoutcl;
private ImageView gps;
private Button saveLocation;
FirebaseAuth fAuth;
String userId, address,state, postalcode, country ,city, district, scity, sstate, spostalcode, scountry, saddress, sdistrict;
Double mLatitude, mLongitude, slatitude, slongitude;
TextView savecurrentlocation;
int i = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_current_location_map);
cityTextView = (TextView) findViewById(R.id.cityname);
AddressTextView = (TextView) findViewById(R.id.addressText);
saveLocation = (Button) findViewById(R.id.confirmlocation);
savecurrentlocation = (TextView) findViewById(R.id.save);
if (requestSinglePermission()) {
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
mapView = mapFragment.getView();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
checkLocation();
}
backbtn = (ImageView) findViewById(R.id.backbtnmap);
backbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
gps = (ImageView) findViewById(R.id.locationgps);
relativeLayoutcl = (RelativeLayout) findViewById(R.id.relativeinvisible);
changebutton = (TextView) findViewById(R.id.changebtn);
changebutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
BottomSheetDialog bottomSheetDialog = new BottomSheetDialog();
bottomSheetDialog.show(getSupportFragmentManager(), "BottomSheetDialog");
}
});
savecurrentlocation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FirebaseFirestore mFireStore = FirebaseFirestore.getInstance();
fAuth = FirebaseAuth.getInstance();
userId = fAuth.getCurrentUser().getUid();
if (i == 1){
Map<String, Object> map = new HashMap<>();
map.put("City", city);
map.put("Address Line 1", address);
map.put("State", state);
map.put("Country", country);
map.put("District", district);
map.put("Postal Code", postalcode);
map.put("Latitude", mLatitude);
map.put("Longitude", mLongitude);
CollectionReference documentReference = mFireStore.collection("users").document(userId).collection("addresses");
documentReference.add(map).addOnCompleteListener(new OnCompleteListener<DocumentReference>() {
@Override
public void onComplete(@NonNull Task<DocumentReference> task) {
if (task.isSuccessful()){
Toast.makeText(currentLocationMapActivity.this, "Saved location first", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(currentLocationMapActivity.this, "Sorry bro", Toast.LENGTH_SHORT).show();
}
}
});
}
if (i == 2){
Map<String, Object> smap = new HashMap<>();
smap.put("City", scity);
smap.put("Address Line 1", saddress);
smap.put("State", sstate);
smap.put("Country", scountry);
smap.put("District", sdistrict);
smap.put("Postal Code", spostalcode);
smap.put("Latitude", slatitude);
smap.put("Longitude", slongitude);
CollectionReference sdocumentReference = mFireStore.collection("users").document(userId).collection("addresses");
sdocumentReference.add(smap).addOnCompleteListener(new OnCompleteListener<DocumentReference>() {
@Override
public void onComplete(@NonNull Task<DocumentReference> stask) {
if (stask.isSuccessful()){
Toast.makeText(currentLocationMapActivity.this, "Saved location second", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(currentLocationMapActivity.this, "Sorry broo", Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
}
private boolean checkLocation() {
if (!isLocationEnabled()) {
showAlert();
}
return isLocationEnabled();
}
private void showAlert() {
final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("Enable Location")
.setMessage("Your Locations Settings is set to 'off'.\nPlease Enable Location to" + "use this app")
.setPositiveButton("Location Settings", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
dialog.show();
}
private boolean isLocationEnabled() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
private boolean requestSinglePermission() {
Dexter.withActivity(this)
.withPermission(Manifest.permission.ACCESS_FINE_LOCATION)
.withListener(new PermissionListener() {
@Override
public void onPermissionGranted(PermissionGrantedResponse permissionGrantedResponse) {
isPermission = true;
}
@Override
public void onPermissionDenied(PermissionDeniedResponse permissionDeniedResponse) {
if (permissionDeniedResponse.isPermanentlyDenied()) {
isPermission = false;
}
}
@Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permissionRequest, PermissionToken permissionToken) {
}
}).check();
return isPermission;
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where 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 is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
@SuppressLint("MissingPermission")
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (latLng != null) {
mMap.clear();
mMap.addMarker(new MarkerOptions().position(latLng).draggable(true).title("Hold and drag marker to change location").draggable(true));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 18F));
mMap.setOnMarkerDragListener(this);
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
mMap.getUiSettings().setCompassEnabled(true);
final View locationButton = ((View) mapView.findViewById(Integer.parseInt("1")).getParent()).findViewById(Integer.parseInt("2"));
if (locationButton != null)
locationButton.setVisibility(View.GONE);
gps.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mMap != null ){
if (locationButton != null)
locationButton.callOnClick();
}
}
});
ViewGroup parent = (ViewGroup) mapView.findViewById(Integer.parseInt("1")).getParent();
View compassButton = parent.getChildAt(4);
RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) compassButton.getLayoutParams();
layoutParams1.setMargins(0, 180, 0, 0 );
}
}
@Override
public void onConnected(@Nullable Bundle bundle) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
return;
}
startLocationUpdates();
mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLocation == null) {
startLocationUpdates();
} else {
//Toast.makeText(this, "Location not Detected", Toast.LENGTH_SHORT).show();
}
}
private void startLocationUpdates() {
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(UPDATE_INTERVAL)
.setFastestInterval(FASTEST_INTERVAL);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
@Override
public void onLocationChanged(Location location) {
cityTextView.setText("Searching....");
AddressTextView.setText("fetching location....");
saveLocation.setEnabled(false);
saveLocation.setAlpha(.3f);
String msg = "Updated Location: " +
Double.toString(location.getLatitude()) + "," +
Double.toString(location.getLongitude());
//Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
latLng = new LatLng(location.getLatitude(), location.getLongitude());
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
try {
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
i = 1;
city = addresses.get(0).getLocality();
state = addresses.get(0).getAdminArea();
postalcode = addresses.get(0).getPostalCode();
country = addresses.get(0).getCountryName();
address = addresses.get(0).getAddressLine(0);
district = addresses.get(0).getSubLocality();
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
if (city == null){
cityTextView.setText("Searching....");
AddressTextView.setText("Fetching location....");
AlertDialog.Builder alertdialogbox = new AlertDialog.Builder(currentLocationMapActivity.this);
alertdialogbox.setTitle("Unable to fetch location");
alertdialogbox.setMessage("Try to search address manually");
alertdialogbox.setPositiveButton("Retry", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
startLocationUpdates();
dialog.cancel();
}
});
alertdialogbox.setNegativeButton("Manual Address", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(getApplicationContext(), AppHome.class);
startActivity(intent);
dialog.cancel();
}
});
AlertDialog alert1 = alertdialogbox.create();
alert1.show();
}
else {
cityTextView.setText(city);
AddressTextView.setText(state + "(" + city + ")" + "," + " " + country + " " + postalcode);
saveLocation.setEnabled(true);
saveLocation.setAlpha(1f);
}
if (state == null){
AddressTextView.setText("(" + city + ")" + "," + " " + country + " " + postalcode);
}
if (postalcode == null){
AddressTextView.setText(state + "(" + city + ")" + "," + " " + country);
}
if (country == null){
AddressTextView.setText(state + "(" + city + ")" + "," + " " + postalcode);
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected void onStart() {
super.onStart();
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
}
@Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
@Override
public void onButtonClicked(String text) {
}
@Override
public void onMarkerDragStart(Marker marker) {
cityTextView.setText("Searching....");
AddressTextView.setText("fetching location....");
saveLocation.setEnabled(false);
saveLocation.setAlpha(.3f);
}
@Override
public void onMarkerDrag(Marker marker) {
}
@Override
public void onMarkerDragEnd(Marker marker) {
try {
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
List<Address> saddresses = geocoder.getFromLocation(marker.getPosition().latitude, marker.getPosition().longitude, 1);
i = 2;
scity = saddresses.get(0).getLocality();
sstate = saddresses.get(0).getAdminArea();
spostalcode = saddresses.get(0).getPostalCode();
scountry = saddresses.get(0).getCountryName();
saddress = saddresses.get(0).getAddressLine(0);
sdistrict = saddresses.get(0).getSubLocality();
slatitude = marker.getPosition().latitude;
slongitude = marker.getPosition().longitude;
if (scity == null){
cityTextView.setText("Searching....");
AddressTextView.setText("Fetching location....");
AlertDialog.Builder alertdialogbox = new AlertDialog.Builder(currentLocationMapActivity.this);
alertdialogbox.setTitle("Unable to fetch location");
alertdialogbox.setMessage("Try to search address manually");
alertdialogbox.setPositiveButton("Retry", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
startLocationUpdates();
dialog.cancel();
}
});
alertdialogbox.setNegativeButton("Manual Address", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(getApplicationContext(), AppHome.class);
startActivity(intent);
dialog.cancel();
}
});
AlertDialog alert1 = alertdialogbox.create();
alert1.show();
}
else {
cityTextView.setText(scity);
AddressTextView.setText(sstate + "(" + scity + ")" + "," + " " + scountry + " " + spostalcode);
saveLocation.setEnabled(true);
saveLocation.setAlpha(1f);
}
if (sstate == null){
AddressTextView.setText("(" + scity + ")" + "," + " " + scountry + " " + spostalcode);
}
if (spostalcode == null){
AddressTextView.setText(sstate + "(" + scity + ")" + "," + " " + scountry);
}
if (scountry == null){
AddressTextView.setText(sstate + "(" + scity + ")" + "," + " " + spostalcode);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}```
import androidx.annotation.NonNull;
导入androidx.annotation.Nullable;
导入androidx.core.app.ActivityCompat;
导入androidx.fragment.app.FragmentActivity;
导入android.Manifest;
导入android.annotation.SuppressLint;
导入android.app.AlertDialog;
导入android.content.Context;
导入android.content.DialogInterface;
导入android.content.Intent;
导入android.content.pm.PackageManager;
导入android.graphics.PorterDuff;
导入android.location.Address;
导入android.location.Geocoder;
导入android.location.location;
导入android.location.LocationManager;
导入android.os.Bundle;
导入android.provider.Settings;
导入android.view.view;
导入android.view.ViewGroup;
导入android.widget.Button;
导入android.widget.ImageView;
导入android.widget.RelativeLayout;
导入android.widget.TextView;
导入android.widget.Toast;
导入com.google.android.gms.common.ConnectionResult;
导入com.google.android.gms.common.api.GoogleAppClient;
导入com.google.android.gms.common.internal.GoogleApiAvailabilityCache;
导入com.google.android.gms.location.LocationListener;
导入com.google.android.gms.location.LocationRequest;
导入com.google.android.gms.location.LocationServices;
导入com.google.android.gms.maps.CameraUpdateFactory;
导入com.google.android.gms.maps.GoogleMap;
导入com.google.android.gms.maps.OnMapReadyCallback;
导入com.google.android.gms.maps.SupportMapFragment;
导入com.google.android.gms.maps.UiSettings;
导入com.google.android.gms.maps.model.BitmapDescriptorFactory;
导入com.google.android.gms.maps.model.CameraPosition;
导入com.google.android.gms.maps.model.LatLng;
导入com.google.android.gms.maps.model.Marker;
导入com.google.android.gms.maps.model.MarkerOptions;
导入com.google.android.gms.tasks.OnCompleteListener;
导入com.google.android.gms.tasks.Task;
导入com.google.firebase.auth.FirebaseAuth;
导入com.google.firebase.firestore.CollectionReference;
导入com.google.firebase.firestore.DocumentReference;
导入com.google.firebase.firestore.FieldValue;
导入com.google.firebase.firestore.FirebaseFirestore;
导入com.karumi.dexter.dexter;
导入com.karumi.dexter.PermissionToken;
导入com.karumi.dexter.listener.PermissionDeniedResponse;
导入com.karumi.dexter.listener.PermissionGrantedResponse;
导入com.karumi.dexter.listener.PermissionRequest;
导入com.karumi.dexter.listener.single.PermissionListener;
导入java.io.IOException;
导入java.util.HashMap;
导入java.util.List;
导入java.util.Locale;
导入java.util.Map;
公共类currentLocationMapActivity扩展了FragmentActivity在MapReadyCallback、GoogleAppClient.ConnectionCallbacks、GoogleAppClient.OnConnectionFailedListener、LocationListener、BottomSheetDialog.BottomSheetListener、GoogleMap.OnMarkerDragListener上实现的碎片{
私有谷歌地图;
私人GoogleapClient MGoogleapClient;
私人位置;
私人位置请求mLocationRequest;
私有com.google.android.gms.location.LocationListener LocationListener;
私有长更新间隔=55000;
专用长最快_间隔=50000;
私人场所经理场所经理;
私有标记选项标记选项;
专用标记;
私人车床,车床,车床G1;
私有布尔许可;
私有视图地图视图;
私有图像视图backbtn;
公共文本视图更改按钮;
私有文本视图cityTextView,地址文本视图;
公共关系;公共关系;
私人影像视图gps;
私有按钮保存位置;
弗斯;
字符串用户ID、地址、州、邮政编码、国家、城市、地区、市、州、州、州、州码、童子军、女童子军、女童子军;
双度、长度、慢度、慢度;
文本视图保存当前位置;
int i=0;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u current\u location\u map);
cityTextView=(TextView)findViewById(R.id.cityname);
AddressTextView=(TextView)findViewById(R.id.addressText);
saveLocation=(按钮)findViewById(R.id.confirmlocation);
savecurrentlocation=(TextView)findViewById(R.id.save);
if(requestSinglePermission()){
//获取SupportMapFragment,并在地图准备好使用时收到通知。
SupportMapFragment mapFragment=(SupportMapFragment)getSupportFragmentManager()
.findFragmentById(R.id.map);
getMapAsync(这个);
mapView=mapFragment.getView();
mgoogleapclient=新的Googleapclient.Builder(此)
.addConnectionCallbacks(此)
.addOnConnectionFailedListener(此)
.addApi(LocationServices.API)
.build();
locationManager=(locationManager)this.getSystemService(Context.LOCATION\u服务);
checkLocation();
}
backbtn=(ImageView)findViewById(R.id.backbtnmap);
backbtn.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
完成();
}
});
gps=(图像视图)findViewById(R.id.locationgps);
relativeLayoutcl=(RelativeLayout)findViewById(R.id.relativeinvisible);
changebutton=(TextView)findViewById(R.id.changebtn);
changebutton.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){