Ближайшие места на картах Google не отображаются. Когда я нажимаю кнопку «Больница», на ней отображаются только сообщения с тостами, когда я нажимаю кнопку «Школа», на ней отображаются только сообщения с тостами, а при нажатии кнопки «Ресторан» - только сообщения с тостами. Также, когда я запускаю код, он не показывает никакой ошибки. Итак, я запутался, что не так с этим кодом. Другой вопрос, я использовал тот же ключ API для Google Maps и Google API это вызовет какие-либо проблемы.
Вот код:
package com.example.maps;
import ...
public class MapsActivity extends FragmentActivity implements
OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener
{
private GoogleMap mMap;
private GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
private Location lastLocation;
private Marker currentUserLocationMarker;
private static final int Request_User_Location_Code = 99;
private double latitude, longitude;
private int ProximityRadius = 10000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
checkUserLocationPermission();
}
// 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);
}
public void onClick(View v)
{
String hospital = "hospital", school = "school", restaurant = "restaurant";
Object transferData[] = new Object[2];
GetNearbyPlaces getNearbyPlaces = new GetNearbyPlaces();
switch (v.getId())
{
case R.id.search_address:
EditText addressField = (EditText) findViewById(R.id.location_search);
String address = addressField.getText().toString();
List<Address> addressList = null;
MarkerOptions userMarkerOptions = new MarkerOptions();
if ( !TextUtils.isEmpty(address))
{
Geocoder geocoder = new Geocoder(this);
try
{
addressList = geocoder.getFromLocationName(address, 6);
if (addressList != null)
{
for (int i = 0; i< addressList.size(); i++)
{
Address userAddress = addressList.get(i);
LatLng latLng = new LatLng(userAddress.getLatitude(), userAddress.getLongitude());
userMarkerOptions.position(latLng);
userMarkerOptions.title(address);
userMarkerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_VIOLET));
mMap.addMarker(userMarkerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(6));;
}
}
else
{
Toast.makeText(this, "Location not found", Toast.LENGTH_SHORT).show();
}
}
catch (IOException e) {
e.printStackTrace();
}
}
else
{
Toast.makeText(this, "Please write the location name you want to search", Toast.LENGTH_SHORT).show();
}
break;
case R.id.hospital_nearby:
mMap.clear();
String url = getUrl(latitude, longitude, hospital);
transferData[0] = mMap;
transferData[1] = url;
getNearbyPlaces.execute(transferData);
Toast.makeText(this, "Searching nearby hospitals", Toast.LENGTH_SHORT).show();
Toast.makeText(this, "Showing nearby hospital", Toast.LENGTH_SHORT).show();
break;
case R.id.school_nearby:
mMap.clear();
url = getUrl(latitude, longitude, school);
transferData[0] = mMap;
transferData[1] = url;
getNearbyPlaces.execute(transferData);
Toast.makeText(this, "Searching nearby school", Toast.LENGTH_SHORT).show();
Toast.makeText(this, "Showing nearby school", Toast.LENGTH_SHORT).show();
break;
case R.id.restaurants_nearby:
mMap.clear();
url = getUrl(latitude, longitude, restaurant);
transferData[0] = mMap;
transferData[1] = url;
getNearbyPlaces.execute(transferData);
Toast.makeText(this, "Searching nearby restaurant", Toast.LENGTH_SHORT).show();
Toast.makeText(this, "Showing nearby restaurant", Toast.LENGTH_SHORT).show();
break;
}
}
private String getUrl(double latitude, double longitude, String nearbyPlace)
{
StringBuilder googleURL = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
googleURL.append("location=" + latitude + "," + longitude);
googleURL.append("&radius=" + ProximityRadius);
googleURL.append("&type=" + nearbyPlace);
googleURL.append("&sensor=true");
googleURL.append("&key=" + "AIzaSyA-ewSczADO0ztObDJC5U1k708JuA2SeRQ");
Log.d("GoogleMapsActivity", "Url = " + googleURL.toString());
return googleURL.toString();
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
public boolean checkUserLocationPermission()
{
if (ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
if (ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.ACCESS_FINE_LOCATION))
{
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, Request_User_Location_Code );
}
else{
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, Request_User_Location_Code );
}
return false;
}
else{
return true;
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
{
switch (requestCode)
{
case Request_User_Location_Code:
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
if (googleApiClient == null)
{
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
}
else
{
Toast.makeText(this, "Permission Denied...", Toast.LENGTH_SHORT).show();
}
return;
}
}
protected synchronized void buildGoogleApiClient()
{
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
googleApiClient.connect();
}
@Override
public void onLocationChanged(Location location)
{
latitude = location.getLatitude();
longitude = location.getLongitude();
lastLocation = location;
if(currentUserLocationMarker != null)
{
currentUserLocationMarker.remove();
}
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Your Location"); markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
currentUserLocationMarker = mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomBy(12));;
if (googleApiClient != null)
{
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient,this);
}
}
@Override
public void onConnected(@Nullable Bundle bundle) {
locationRequest = new LocationRequest();
locationRequest.setInterval(1100);
locationRequest.setFastestInterval(1100);
locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
}