我已经在Google地图上展示了当前位置,但是当选择“自动定位城市”并在Google地图上显示该位置时,我希望将标记固定在地图中心。
我的代码如下:
public class PostAdsFragmentFifth extends Fragment implements View.OnClickListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = PostAdsFragmentFifth.class.getSimpleName();
private CustomTextView tvBackBtn;
PlaceAutocompleteFragment autocompleteFragment;
private GoogleMap mMap;
Address address;
protected GoogleApiClient mGoogleApiClient;
private Marker marker;
private SupportMapFragment mapFragment;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_post_slide5, container, false);
checkGpsEnabled();
setGooglePlaces();
mapFragment = (SupportMapFragment) this.getChildFragmentManager()
.findFragmentById(R.id.map);
tvBackBtn = (CustomTextView) getActivity().findViewById(R.id.tvBack);
tvBackBtn.setVisibility(View.VISIBLE);
tvBackBtn.setOnClickListener(this);
return view;
}
@Override
public void onStart() {
super.onStart();
checkPermissions();
}
@Override
public void onDestroy() {
super.onDestroy();
if (mGoogleApiClient != null)
mGoogleApiClient.disconnect();
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.tvBack:
MixPanelEvents.addMixPanelEvents(getActivity(), "Pet Address for Back");
if (getUserVisibleHint())
((PostAdsActivity) getActivity()).gotoNext(4);
break;
}
}
private void setGooglePlaces() {
autocompleteFragment = (PlaceAutocompleteFragment) getActivity().getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
autocompleteFragment.setHint(getResources().getString(R.string.address_hint_toast));
AutocompleteFilter typeFilter = new AutocompleteFilter.Builder()
.setTypeFilter(AutocompleteFilter.TYPE_FILTER_ADDRESS)
.build();
autocompleteFragment.setFilter(typeFilter);
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
@Override
public void onPlaceSelected(Place place) {
address = new Address();
address.setLatitude(place.getLatLng().latitude);
address.setLongitude(place.getLatLng().longitude);
address.setAddress(place.getAddress().toString());
address.setLandmark(place.getName().toString());
PostAdsActivity.postData.setAddress(address);
}
@Override
public void onError(Status status) {
// TODO: Handle the error.
LogUtils.i(TAG, "An error occurred: " + status);
}
});
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addApi(LocationServices.API)
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.build();
mGoogleApiClient.connect();
}
@Override
public void onConnected(Bundle bundle) {
Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
double lat = mLastLocation.getLatitude();
double lng = mLastLocation.getLongitude();
if (lat != 0 && lng != 0) {
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 16.0f));
convertLocationToAddress(new LatLng(lat, lng));
if (marker != null) {
MarkerOptions markerOptions = new MarkerOptions().position(new LatLng(lat, lng));
marker = mMap.addMarker(markerOptions);
}
}
}
}
private void checkPermissions() {
if (Build.VERSION.SDK_INT >= 23 && getActivity().checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& getActivity().checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ArrayList<String> permissons = new ArrayList<>();
permissons.add(Manifest.permission.ACCESS_FINE_LOCATION);
permissons.add(Manifest.permission.ACCESS_COARSE_LOCATION);
String[] items = permissons.toArray(new String[permissons.size()]);
requestPermissions(items, 4);
} else {
mapFragment.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
setUpMap();
buildGoogleApiClient();
}
});
}
}
private void setUpMap() {
if (Utility.isAppInstalled(getActivity(), "com.google.android.apps.maps")) {
mMap.setMyLocationEnabled(true);
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
@Override
public boolean onMarkerClick(Marker marker) {
LatLng currentLocation = marker.getPosition();
convertLocationToAddress(currentLocation);
return false;
}
});
mMap.setOnMarkerDragListener(new GoogleMap.OnMarkerDragListener() {
@Override
public void onMarkerDragStart(Marker marker) {
}
@Override
public void onMarkerDragEnd(Marker marker) {
LatLng currentLocation = marker.getPosition();
convertLocationToAddress(currentLocation);
}
@Override
public void onMarkerDrag(Marker marker) {
}
});
mMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
@Override
public void onMapLoaded() {
LogUtils.e("TAG", mMap.getCameraPosition().target.toString());
convertLocationToAddress(mMap.getCameraPosition().target);
marker = mMap.addMarker(new MarkerOptions()
.position(new LatLng(mMap.getCameraPosition().target.latitude, mMap.getCameraPosition().target.longitude))
.title("Marker")
.draggable(true)
.snippet("Location")
.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
}
});
}
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 4) {
for (int a = 0; a < permissions.length; a++) {
if (grantResults[a] != PackageManager.PERMISSION_GRANTED) {
continue;
}
switch (permissions[a]) {
case Manifest.permission.ACCESS_FINE_LOCATION:
mapFragment.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
setUpMap();
buildGoogleApiClient();
}
});
break;
case Manifest.permission.ACCESS_COARSE_LOCATION:
mapFragment.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
setUpMap();
buildGoogleApiClient();
}
});
break;
}
}
}
}
private void convertLocationToAddress(LatLng latLong) {
try {
Geocoder geocoder;
List<android.location.Address> addresses;
geocoder = new Geocoder(getActivity(), Locale.getDefault());
addresses = geocoder.getFromLocation(latLong.latitude, latLong.longitude, 1);
LogUtils.d("Address", addresses.toString());
/*address.setAddress(addresses.get(0).getAddressLine(0));
if (addresses.get(0).getLocality() != null) {
address.setCity(addresses.get(0).getLocality());
} else {
address.setCity("");
}
if (addresses.get(0).getAdminArea() != null) {
address.setState(addresses.get(0).getAdminArea());
} else {
address.setState("");
}
address.setLatitude(latLong.latitude);
address.setLongitude(latLong.longitude);
if (addresses.get(0).getPostalCode() != null) {
// address.setPinCode(addresses.get(0).getPostalCode());
}*/
} catch (Exception e) {
e.printStackTrace();
}
}
private void checkGpsEnabled() {
LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
boolean gps_enabled = false;
boolean network_enabled = false;
try {
gps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
network_enabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!gps_enabled && !network_enabled) {
AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
dialog.setTitle(getResources().getString(R.string.location_gps_alretDialog_tittle));
dialog.setMessage(getResources().getString(R.string.location_gps_alretDialog_msg));
dialog.setPositiveButton(this.getResources().getString(R.string.yes), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
MixPanelEvents.addMixPanelEvents(getActivity(), getResources().getString(R.string.location_gps_alretDialog_tittle));
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(myIntent, 1);
}
});
dialog.setNegativeButton(this.getString(R.string.no), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
paramDialogInterface.dismiss();
}
});
dialog.show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}