这是我的代码:
public class Mapsactivity extends AppCompatactivity implements OnmapReadyCallback,LocationListener,GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener {
GoogleMap mMap;
SupportMapFragment mapFragment;
LocationRequest mLocationRequest;
GoogleApiClient client;
Location mLastLocation;
Marker mCurrLocationmarker;
LatLng latLongCurrent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
getSupportactionBar().setTitle("Map location");
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
public void findRestaurant(View view) {
StringBuilder stringBuilder = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
stringBuilder.append("location=" + latLongCurrent.latitude + "," + latLongCurrent.longitude); //error attempt to read from field 'double...on a null object reference
stringBuilder.append("&radius=" + 1000);
stringBuilder.append("&keyword=" + "restaurant");
stringBuilder.append("&key=" + getResources().getString(R.string.google_places_key));
String url = stringBuilder.toString();
Object dataTransfer[] = new Object[2];
dataTransfer[0] = mMap;
dataTransfer[1] = url;
NearbySearch nearbySearch = new NearbySearch(this);
nearbySearch.execute(dataTransfer);
}
@Override
public void onPause() {
super.onPause();
//stop location updates when activity is no longer active
if (client != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(client,this);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.map_options,menu);
return true;
}
@Override
public void onmapReady(GoogleMap googleMap) {
mMap = googleMap;
//Initializing the Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,Manifest.permission.accESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
//Location Permission already granted
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
} else {
//Request Location Permission
checkLocationPermission();
}
} else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient() {
client = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
client.connect();
}
@Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setfastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BAlanceD_POWER_accURACY);
if (ContextCompat.checkSelfPermission(this,Manifest.permission.accESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(client,mLocationRequest,this);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Change the map type based on the user's selection.
switch (item.getItemId()) {
case R.id.normal_map:
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
return true;
case R.id.hybrid_map:
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
return true;
case R.id.satellite_map:
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
return true;
case R.id.terrain_map:
mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mCurrLocationmarker != null) {
mCurrLocationmarker.remove();
}
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(),location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("My current Position");
mCurrLocationmarker = mMap.addMarker(markerOptions);
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
private void checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this,Manifest.permission.accESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (activityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.accESS_FINE_LOCATION)) {
new AlertDialog.Builder(Mapsactivity.this)
.setTitle("Location Permission Needed")
.setMessage("This app needs the Location permission,please accept this to use the location functionality")
.setPositiveButton("OK",new DialogInterface.OnClicklistener() {
@Override
public void onClick(DialogInterface dialogInterface,int i) {
//Prompt the user once explanation has been shown
activityCompat.requestPermissions(Mapsactivity.this,new String[]{Manifest.permission.accESS_FINE_LOCATION},MY_PERMISSIONS_REQUEST_LOCATION);
}
}).create().show();
} else {
// No explanation needed,we can request the permission.
activityCompat.requestPermissions(this,MY_PERMISSIONS_REQUEST_LOCATION);
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode,String permissions[],int[] grantResults) {
super.onRequestPermissionsResult(requestCode,permissions,grantResults);
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled,the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this,Manifest.permission.accESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (client == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
Toast.makeText(this,"Permission is denied",Toast.LENGTH_LONG).show();
}
return;
}
}
}
private void moveCamera(LatLng latLang,float zoom,String title) {
mMap.moveCamera(CameraUpdateFactory.newLatLngzoom(latLang,zoom));
//writing the code to drop the pin or marker
MarkerOptions options = new MarkerOptions().position(latLang).title(title);
mMap.addMarker(options);
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
}
这是我的类 NearbySearch.java
代码如下:
public class NearbySearch extends AsyncTask<Object,String,String> {
GoogleMap mMap;
String url;
InputStream is;
BufferedReader bufferedReader;
StringBuilder stringBuilder;
String data;
public NearbySearch(Mapsactivity mapsactivity) {
}
@Override
protected String doInBackground(Object... objects) {
//requesting for the response from the google places API
mMap = (GoogleMap) objects[0];
try {
URL myUrl = new URL(url);
HttpURLConnection httpURLConnection = (HttpURLConnection) myUrl.openConnection();
is = httpURLConnection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(is));
String line = "";
stringBuilder = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}
//Receiving the data from json
data = stringBuilder.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
@Override
protected void onPostExecute(String s) {
try {
JSONObject parentObject = new JSONObject(s);
JSONArray resultArray = parentObject.getJSONArray("results");
for (int i = 0; i < resultArray.length(); i++) {
JSONObject jsonObject = resultArray.getJSONObject(i);
JSONObject locationObject = jsonObject.getJSONObject("geometry").getJSONObject("location");
String latitude = jsonObject.getString("lat");
String longitude = jsonObject.getString("lng");
JSONObject nameObject = resultArray.getJSONObject(i);
String nameRestaurant = nameObject.getString("name");
String vicinity = nameObject.getString("vicinity");
LatLng latLng = new LatLng(Double.parseDouble(latitude),Double.parseDouble(longitude));
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.title(vicinity);
markerOptions.position(latLng);
mMap.addMarker(markerOptions);
}
} catch (JSONException e) {
e.printStackTrace();
}
super.onPostExecute(s);
}
}
我已成功获取用户的当前位置,但无法找到从当前位置查找附近餐馆的解决方案。请帮助摆脱它,因为我在这里被困了 2 天。请告诉我是否还有其他解决方案。谢谢!