2017-07-24 72 views
0

我正在使用nearbyPlaces網絡服務,我遇到問題,我在地圖上爲它找到的每個藥物放置了一個標記,但攝像機始終移動到標記並且它不會停留在當前用戶位置點上。當在地圖活動上放置標記時,攝像機移動到標記

這是代碼

public class GetNearbyPlacesData extends AsyncTask<Object, String, String> { 

String googlePlacesData; 
GoogleMap mMap; 
String url; 

@Override 
protected String doInBackground(Object... params) { 
    try { 
     Log.d("GetNearbyPlacesData", "doInBackground entered"); 
     mMap = (GoogleMap) params[0]; 
     url = (String) params[1]; 
     DownloadUrl downloadUrl = new DownloadUrl(); 
     googlePlacesData = downloadUrl.readUrl(url); 
     Log.d("GooglePlacesReadTask", "doInBackground Exit"); 
    } catch (Exception e) { 
     Log.d("GooglePlacesReadTask", e.toString()); 
    } 
    return googlePlacesData; 
} 

@Override 
protected void onPostExecute(String result) { 
    Log.d("GooglePlacesReadTask", "onPostExecute Entered"); 
    List<HashMap<String, String>> nearbyPlacesList = null; 
    DataParser dataParser = new DataParser(); 
    nearbyPlacesList = dataParser.parse(result); 
    ShowNearbyPlaces(nearbyPlacesList); 
    Log.d("GooglePlacesReadTask", "onPostExecute Exit"); 
} 

private void ShowNearbyPlaces(List<HashMap<String, String>> nearbyPlacesList) { 
    for (int i = 0; i < nearbyPlacesList.size(); i++) { 
     Log.d("onPostExecute","Entered into showing locations"); 
     MarkerOptions markerOptions = new MarkerOptions(); 
     markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)); 
     HashMap<String, String> googlePlace = nearbyPlacesList.get(i); 
     double lat = Double.parseDouble(googlePlace.get("lat")); 
     double lng = Double.parseDouble(googlePlace.get("lng")); 
     String placeName = googlePlace.get("place_name"); 
     String vicinity = googlePlace.get("vicinity"); 
     LatLng latLng = new LatLng(lat, lng); 
     markerOptions.position(latLng); 
     markerOptions.title(placeName + " : " + vicinity); 
     mMap.addMarker(markerOptions); 
     //markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)); 
     //move map camera 
     mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); 
     mMap.animateCamera(CameraUpdateFactory.zoomTo(14.0f)); 
    } 
} 
} 

public class NearbyPharmaciesFragment extends Fragment implements OnMapReadyCallback, 
    GoogleApiClient.ConnectionCallbacks, 
    GoogleApiClient.OnConnectionFailedListener, 
    LocationListener { 
private GoogleMap mMap; 
double latitude; 
double longitude; 
private int PROXIMITY_RADIUS = 1000; 
LocationManager locationManager; 
GoogleApiClient mGoogleApiClient; 
AlertDialog alert = null; 
Location mLastLocation; 
Marker mCurrLocationMarker; 
LocationRequest mLocationRequest; 
@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) { 
    View rootView = inflater.inflate(R.layout.fragment_nearby_pharmacies, container, false); 
    locationManager = (LocationManager) getActivity().getSystemService(LOCATION_SERVICE); 
    if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { 
     AlertNoGps(); 
    } 
    // Inflate the layout for this fragment 
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 
     checkLocationPermission(); 
    } 

    //Check if Google Play Services Available or not 
    if (!CheckGooglePlayServices()) { 
     Log.d("onCreate", "Finishing test case since Google Play Services are not available"); 
     //finish(); 
    } 
    else { 
     Log.d("onCreate","Google Play Services available."); 
    } 

    // Obtain the SupportMapFragment and get notified when the map is ready to be used. 
    //SupportMapFragment mapFragment = (SupportMapFragment) getActivity().getSupportFragmentManager() 
    SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager() 
      .findFragmentById(R.id.map); 
    mapFragment.getMapAsync(this); 
    return rootView; 
} 
private boolean CheckGooglePlayServices() { 
    GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance(); 
    int result = googleAPI.isGooglePlayServicesAvailable(getActivity()); 
    if(result != ConnectionResult.SUCCESS) { 
     if(googleAPI.isUserResolvableError(result)) { 
      googleAPI.getErrorDialog(getActivity(), result, 
        0).show(); 
     } 
     return false; 
    } 
    return true; 
} 



/** 
* 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; 
    mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); 

    //Initialize Google Play Services 
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 
     if (ContextCompat.checkSelfPermission(getActivity(), 
       Manifest.permission.ACCESS_FINE_LOCATION) 
       == PackageManager.PERMISSION_GRANTED) { 
      buildGoogleApiClient(); 
      mMap.setMyLocationEnabled(true); 
     } 
    } 
    else { 
     buildGoogleApiClient(); 
     mMap.setMyLocationEnabled(true); 
    } 


} 

protected synchronized void buildGoogleApiClient() { 
    mGoogleApiClient = new GoogleApiClient.Builder(getActivity()) 
      .addConnectionCallbacks(this) 
      .addOnConnectionFailedListener(this) 
      .addApi(LocationServices.API) 
      .build(); 
    mGoogleApiClient.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(getActivity(), 
      Manifest.permission.ACCESS_FINE_LOCATION) 
      == PackageManager.PERMISSION_GRANTED) { 
     LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this); 
    } 
} 

private String getUrl(double latitude, double longitude, String nearbyPlace) { 

    StringBuilder googlePlacesUrl = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?"); 
    googlePlacesUrl.append("location=" + latitude + "," + longitude); 
    googlePlacesUrl.append("&radius=" + PROXIMITY_RADIUS); 
    googlePlacesUrl.append("&type=" + nearbyPlace); 
    googlePlacesUrl.append("&sensor=true"); 
    googlePlacesUrl.append("&key=" + "API_KEY"); 
    Log.d("getUrl", googlePlacesUrl.toString()); 
    return (googlePlacesUrl.toString()); 
} 

@Override 
public void onConnectionSuspended(int i) { 

} 

@Override 
public void onLocationChanged(Location location) { 
    Log.d("onLocationChanged", "entered"); 

    mLastLocation = location; 
    if (mCurrLocationMarker != null) { 
     mCurrLocationMarker.remove(); 
    } 

    //Place current location marker 
    latitude = location.getLatitude(); 
    longitude = location.getLongitude(); 
    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude()); 
    MarkerOptions markerOptions = new MarkerOptions(); 
    markerOptions.position(latLng); 
    markerOptions.title("Current Position"); 
    markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA)); 
    mCurrLocationMarker = mMap.addMarker(markerOptions); 

    //move map camera 
    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); 
    float zoom=11.0f; 
    mMap.animateCamera(CameraUpdateFactory.zoomTo(zoom)); 
    //Toast.makeText(getActivity(),"Your Current Location", Toast.LENGTH_LONG).show(); 
    mMap.clear(); 
    String pharmacy = "pharmacy"; 
    String url = getUrl(latitude, longitude, pharmacy); 
    Object[] DataTransfer = new Object[2]; 
    DataTransfer[0] = mMap; 
    DataTransfer[1] = url; 
    if (new InternetWatcher().isConnectedToNetwork(getActivity())){ 
     GetNearbyPlacesData getNearbyPlacesData = new GetNearbyPlacesData(); 
     getNearbyPlacesData.execute(DataTransfer); 
    }else{ 
     Toast.makeText(getActivity(), R.string.internet_para_ver_farmacias, Toast.LENGTH_LONG).show(); 
     getActivity().onBackPressed(); 
    } 





    //stop location updates 
    if (mGoogleApiClient != null) { 
     LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this); 
     Log.d("onLocationChanged", "Removing Location Updates"); 
    } 
    Log.d("onLocationChanged", "Exit"); 

} 

@Override 
public void onConnectionFailed(ConnectionResult connectionResult) { 

} 

public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99; 
public boolean checkLocationPermission(){ 
    if (ContextCompat.checkSelfPermission(getActivity(), 
      Manifest.permission.ACCESS_FINE_LOCATION) 
      != PackageManager.PERMISSION_GRANTED) { 

     // Asking user if explanation is needed 
     if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), 
       Manifest.permission.ACCESS_FINE_LOCATION)) { 

      // Show an explanation to the user *asynchronously* -- don't block 
      // this thread waiting for the user's response! After the user 
      // sees the explanation, try again to request the permission. 

      //Prompt the user once explanation has been shown 
      ActivityCompat.requestPermissions(getActivity(), 
        new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 
        MY_PERMISSIONS_REQUEST_LOCATION); 


     } else { 
      // No explanation needed, we can request the permission. 
      ActivityCompat.requestPermissions(getActivity(), 
        new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 
        MY_PERMISSIONS_REQUEST_LOCATION); 
     } 
     return false; 
    } else { 
     return true; 
    } 
} 

@Override 
public void onRequestPermissionsResult(int requestCode, 
             String permissions[], int[] 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) { 

       // permission was granted. Do the 
       // contacts-related task you need to do. 
       if (ContextCompat.checkSelfPermission(getActivity(), 
         Manifest.permission.ACCESS_FINE_LOCATION) 
         == PackageManager.PERMISSION_GRANTED) { 

        if (mGoogleApiClient == null) { 
         buildGoogleApiClient(); 
        } 
        mMap.setMyLocationEnabled(true); 
       } 

      } else { 

       // Permission denied, Disable the functionality that depends on this permission. 
       Toast.makeText(getActivity(), "permission denied", Toast.LENGTH_LONG).show(); 
      } 
      return; 
     } 

     // other 'case' lines to check for other permissions this app might request. 
     // You can add here other case statements according to your requirement. 
    } 
} 

private void AlertNoGps() { 
    final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); 
    builder.setMessage(R.string.gps_no_activado_dialogo) 
      .setCancelable(false) 
      .setPositiveButton(R.string.si_gps, new DialogInterface.OnClickListener() { 
       public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id) { 
        startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)); 
       } 
      }) 
      .setNegativeButton("No", new DialogInterface.OnClickListener() { 
       public void onClick(final DialogInterface dialog, @SuppressWarnings("unused") final int id) { 
        getActivity().onBackPressed(); 
        Toast.makeText(getActivity(), R.string.gps_Required, Toast.LENGTH_LONG).show(); 
        dialog.cancel(); 
       } 
      }); 
    alert = builder.create(); 
    alert.show(); 
} 

任何幫助嗎?在此先感謝

回答

2

您發佈的代碼包括這些行:

//move map camera 
    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); 
    mMap.animateCamera(CameraUpdateFactory.zoomTo(14.0f)); 

聽起來像是你不想要移動攝像機,所以你應該將其刪除。

+0

我已經完成了,但添加完所有藥房標記後,相機仍然沒有將當前用戶的位置放在中心位置 –