2016-03-16 4 views
1

Я знаю, что есть много проблем по этой проблеме, но ничего не дает мне хорошего ответа. Функция onLocationChanged швов никогда не вызывается.Android Google Maps onLocationChanged не называется

@Override 
public void onMapReady(GoogleMap googleMap) { 
    mMap = googleMap; 
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && 
      ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
     return; 
    } 
    mMap.setMyLocationEnabled(true); 
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
    Criteria criteria = new Criteria(); 
    String provider = locationManager.getBestProvider(criteria, true); 

    LocationListener locationListener = new LocationListener() { 
     @Override 
     public void onLocationChanged(Location location) { 
      Toast.makeText(getApplicationContext(), "New Location", Toast.LENGTH_SHORT).show(); 
      LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude()); 
      mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); 
      mMap.animateCamera(CameraUpdateFactory.zoomTo(20)); 
      mMap.addMarker(new MarkerOptions().position(latLng).title("Jesteś tutaj!")); 
     } 

     /* ... */ 
    }; 
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 2, locationListener); 
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 3000, 2, locationListener); 
} 

Что я сделал не так?

ответ

1
First of all you need to run your app in a real device rather then virtual device and by keeping GPS on from settings. 

then you can use the following methods that did the work for me. 

    private void createMap() 
    { 


     TotalDistance.setText("Distance:"); 
     SupportMapFragment supportMapFragment=(SupportMapFragment)getChildFragmentManager().findFragmentById(R.id.map); 
     //SupportMapFragment fm = (SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map); 
     googleMap=supportMapFragment.getMap(); 

/*  googleMap = ((SupportMapFragment) MainActivity.fragmentManager 
       .findFragmentById(R.id.map)).getMap();*/ 
     locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE); 
     // Creating a criteria object to retrieve provider 
     Criteria criteria = new Criteria(); 

     // Getting the name of the best provider 
     provider = locationManager.getBestProvider(criteria, true); 

     // Getting Current Location 
     if (ActivityCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
      // TODO: Consider calling 
      // ActivityCompat#requestPermissions 
      // here to request the missing permissions, and then overriding 
      // public void onRequestPermissionsResult(int requestCode, String[] permissions, 
      //           int[] grantResults) 
      // to handle the case where the user grants the permission. See the documentation 
      // for ActivityCompat#requestPermissions for more details. 
      return; 
     } 

     location = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER); 

     googleMap.getUiSettings().setRotateGesturesEnabled(false); 


     marker = new MarkerOptions().position(new LatLng(location.getLatitude(), location.getLongitude())).title(location.getLatitude() + " " + location.getLongitude()); 
     googleMap.addMarker(marker); 
     CameraPosition cameraPosition = new CameraPosition.Builder().target(new LatLng(location.getLatitude(), location.getLongitude())).zoom(15).build(); 
     googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)); 

     googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN); 
     origin_latLng = new LatLng(location.getLatitude(), location.getLongitude()); 



    } 
    private void intializeMap(Context context) { 
     int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity()); 

     // Showing status 
     if (status != ConnectionResult.SUCCESS) { // Google Play Services are not available 

      int requestCode = 10; 
      Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, getActivity(), requestCode); 
      dialog.show(); 

     } else { // Google Play Services are available 

      // Getting reference to the SupportMapFragment of activity_main.xml 

      if (ActivityCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
       // TODO: Consider calling 
       // ActivityCompat#requestPermissions 
       // here to request the missing permissions, and then overriding 
       // public void onRequestPermissionsResult(int requestCode, String[] permissions, 
       //           int[] grantResults) 
       // to handle the case where the user grants the permission. See the documentation 
       // for ActivityCompat#requestPermissions for more details. 
       return; 
      } 
      googleMap.setMyLocationEnabled(true); 
      googleMap.clear(); 

      if (location != null) { 
       onLocationChanged(location); 
      } 


      locationManager.requestLocationUpdates(provider, 2000, 1, YOUR ACTIVITY REFERENCE); 
      googleMap.stopAnimation(); 

     } 
    } 

    @Override 
    public void onLocationChanged(Location location) { 


     // Getting latitude of the current location 
     double latitude = location.getLatitude(); 
     double longitude = location.getLongitude(); 
     finalLatlang=new LatLng(latitude,longitude); 
     // userlatLang.add(finalLatlang); 

     CameraPosition cameraPosition = new CameraPosition.Builder().target(finalLatlang).zoom(15).build(); 
     googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)); 
     Log.d("Latitude", " " + latitude); 
     Log.d("Longitude", " " + longitude); 

     // Showing the current location in Google Map 
     googleMap.moveCamera(CameraUpdateFactory.newLatLng(finalLatlang)); 


     if(flag==1) { 

      // Zoom in the Google Map 
      googleMap.animateCamera(CameraUpdateFactory.zoomTo(15)); 
      flag++; 
     } 

    } 

Также Pls не реализует LocationListener в вашей деятельности или фрагмента

+0

Im немым .... Не запущен GPS :)) ТНХ –

0
Criteria crit = new Criteria(); 
crit.setAccuracy(Criteria.ACCURACY_FINE); 
String best = mgr.getBestProvider(crit, false); 

выше, чтобы получить лучший провайдер.

Вы можете предоставить свое местонахождениеManager request in onResume();

@Override public void onResume() { 
super.onResume(); 
locationManager.requestLocationUpdates(, 10000, 1, locationListener);} 

Надеюсь, это может вам помочь.

+0

Нет изменений:/THx –

Смежные вопросы