这是我的代码在这里,我试图在Fragment中使用google map,这里的错误在
LocationServices.FusedLocationApi.requestLocationUpdates(client, locationRequest, this);
我尝试使用getActivity()
代替 this ,但仍然无法正常工作:
package com.example.dell.jsonexp;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
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.model.BitmapDescriptorFactory;
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 java.io.IOException;
import java.util.List;
public abstract class MapsActivity extends Fragment implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener,LocationListener{
private GoogleMap mMap;
private GoogleApiClient client;
private LocationRequest locationRequest;
private Location lastlocation;
private Marker currentLocationmMarker;
public static final int REQUEST_LOCATION_CODE = 99;
int PROXIMITY_RADIUS = 10000;
double latitude,longitude;
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_maps, container, false);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
checkLocationPermission();
//error in above line
}
SupportMapFragment mapFragment = (SupportMapFragment)
getActivity().getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch(requestCode)
{
case REQUEST_LOCATION_CODE:
if(grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
if(ContextCompat.checkSelfPermission(getActivity(),Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
if(client == null)
{
bulidGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
}
else
{
Toast.makeText(getActivity(),"Permission Denied" , Toast.LENGTH_LONG).show();
}
}
}
/**
* 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.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
bulidGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
protected synchronized void bulidGoogleApiClient() {
client = new GoogleApiClient.Builder(getActivity()).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
client.connect();
}
@Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
lastlocation = location;
if(currentLocationmMarker != null)
{
currentLocationmMarker.remove();
}
Log.d("lat = ",""+latitude);
LatLng latLng = new LatLng(location.getLatitude() , location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Location");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
currentLocationmMarker = mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomBy(10));
if(client != null)
{
LocationServices.FusedLocationApi.removeLocationUpdates(client,this);
}
}
public void onClick(View v)
{
Object dataTransfer[] = new Object[2];
GetNearbyPlacesData getNearbyPlacesData = new GetNearbyPlacesData();
switch(v.getId())
{
case R.id.B_search:
EditText tf_location = v.findViewById(R.id.TF_location);
String location = tf_location.getText().toString();
List<Address> addressList;
if(!location.equals(""))
{
Geocoder geocoder = new Geocoder(getActivity());
try {
addressList = geocoder.getFromLocationName(location, 5);
if(addressList != null)
{
for(int i = 0;i<addressList.size();i++)
{
LatLng latLng = new LatLng(addressList.get(i).getLatitude() , addressList.get(i).getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(location);
mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(10));
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
break;
case R.id.B_hopistals:
mMap.clear();
String hospital = "hospital";
String url = getUrl(latitude, longitude, hospital);
dataTransfer[0] = mMap;
dataTransfer[1] = url;
getNearbyPlacesData.execute(dataTransfer);
Toast.makeText(getActivity(), "Showing Nearby Hospitals", Toast.LENGTH_SHORT).show();
break;
case R.id.B_schools:
mMap.clear();
String school = "school";
url = getUrl(latitude, longitude, school);
dataTransfer[0] = mMap;
dataTransfer[1] = url;
getNearbyPlacesData.execute(dataTransfer);
Toast.makeText(getActivity(), "Showing Nearby Schools", Toast.LENGTH_SHORT).show();
break;
case R.id.B_restaurants:
mMap.clear();
String resturant = "restuarant";
url = getUrl(latitude, longitude, resturant);
dataTransfer[0] = mMap;
dataTransfer[1] = url;
getNearbyPlacesData.execute(dataTransfer);
Toast.makeText(getActivity(), "Showing Nearby Restaurants", Toast.LENGTH_SHORT).show();
break;
case R.id.B_to:
}
}
private String getUrl(double latitude , double longitude , String nearbyPlace)
{
StringBuilder googlePlaceUrl = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
googlePlaceUrl.append("location="+latitude+","+longitude);
googlePlaceUrl.append("&radius="+PROXIMITY_RADIUS);
googlePlaceUrl.append("&type="+nearbyPlace);
googlePlaceUrl.append("&sensor=true");
googlePlaceUrl.append("&key="+"AIzaSyfw7sMb73Mr88L91Jqh3tuE4mKsE");
Log.d("MapsActivity", "url = "+googlePlaceUrl.toString());
return googlePlaceUrl.toString();
}
@Override
public void onConnected(@Nullable Bundle bundle) {
locationRequest = new LocationRequest();
locationRequest.setInterval(100);
locationRequest.setFastestInterval(1000);
locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if(ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION ) == PackageManager.PERMISSION_GRANTED)
{
LocationServices.FusedLocationApi.requestLocationUpdates(client, locationRequest, this);
//error in above line
}
}
public boolean checkLocationPermission()
{
if(ContextCompat.checkSelfPermission(getActivity(),Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED )
{
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),Manifest.permission.ACCESS_FINE_LOCATION))
{
ActivityCompat.requestPermissions(getActivity(),new String[] {Manifest.permission.ACCESS_FINE_LOCATION },REQUEST_LOCATION_CODE);
}
else
{
ActivityCompat.requestPermissions(getActivity(),new String[] {Manifest.permission.ACCESS_FINE_LOCATION },REQUEST_LOCATION_CODE);
}
return false;
}
else
return true;
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
}
在这里,我在`checkLocationPermission()中收到错误,我不知道为什么,但是我怀疑这是由于权限所致。