2016-11-12 43 views
0

我創建了一個Map Activity,我希望當用戶輸入一個地方的名字時,他會提出各種各樣的地方。當用戶做出任何選擇時,地圖應該位於選定的位置。我已經使用PlaceSelectionListener相同。雖然我能夠獲得緯度和經度,但地圖似乎並未定位。它需要先前設置的位置。我附上了我的代碼以供參考。onMapReady不能在android

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback { 

    private GoogleMap mMap; 
    MapDialog mapDialog; 
    Button button; 
    TextView textView; 
    LocationManager mLocationManager; 
    GooglePlacesAutocompleteAdapter dataAdapter; 
    EditText et; 
    ListView listView; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_maps); 
     // Obtain the SupportMapFragment and get notified when the map is ready to be used. 
     button = (Button) findViewById(R.id.button); 
     textView = (TextView) findViewById(R.id.text_view); 
     button.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       button.setVisibility(View.INVISIBLE); 
       Location location = getLastKnownLocation(); 
       if (location != null) { 
        LatLng userLocation = new LatLng(location.getLatitude(), location.getLongitude()); 
        textView.setVisibility(View.VISIBLE); 
        textView.setText(getAddress(getApplicationContext(), userLocation.latitude, userLocation.longitude)); 
       } 
      } 
     }); 


     AlertDialog.Builder builder = new AlertDialog.Builder(this); 
     builder.setTitle("Turn on Location").setPositiveButton("OK", new DialogInterface.OnClickListener() { 
      @Override 
      public void onClick(DialogInterface dialogInterface, int i) { 
       Intent onGPS = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
       startActivity(onGPS); 
      } 
     }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
      @Override 
      public void onClick(DialogInterface dialogInterface, int i) { 
       dialogInterface.dismiss(); 
      } 
     }).setMessage("Turn on Location services to access the application"); 

     int off = 0; 
     try { 
      off = Settings.Secure.getInt(getContentResolver(), Settings.Secure.LOCATION_MODE); 

     } catch (Settings.SettingNotFoundException e) { 
      e.printStackTrace(); 
     } 
     if (off == 0) { 
      builder.show(); 
     } else { 
      SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() 
        .findFragmentById(R.id.map); 
      mapFragment.getMapAsync(this); 
     } 


     PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment) this.getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment); 
     autocompleteFragment.setOnPlaceSelectedListener(_placeSelectedListener); 
    } 

    @Override 
    protected void onResume() { 
     super.onResume(); 
     Log.e("TAG", "onResume"); 
     SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() 
       .findFragmentById(R.id.map); 
     mapFragment.getMapAsync(this); 
    } 

    /** 
    * 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. 
    */ 

    private PlaceSelectionListener _placeSelectedListener = new PlaceSelectionListener() { 
     @Override 
     public void onPlaceSelected(Place place) { 
      Log.e("TAG", "place is " + String.valueOf(place.getLatLng().latitude + " " + place.getLatLng().longitude)); 
      final Place xyz=place; 

      getWindow().getDecorView().findViewById(R.id.map).invalidate(); 

      final OnMapReadyCallback onMapReadyCallback = new OnMapReadyCallback() { 
       @Override 
       public void onMapReady(GoogleMap googleMap) { 
        mMap = googleMap; 

        // Add a marker in Sydney and move the camera 
        LatLng sydney = new LatLng(xyz.getLatLng().latitude, xyz.getLatLng().longitude); 
        mMap.addMarker(new MarkerOptions().position(sydney).title("Current Location")); 
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney)); 
        mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(xyz.getLatLng(), 15)); 
        Log.e("GAT","Address "+getAddress(getApplicationContext(),xyz.getLatLng().latitude, xyz.getLatLng().longitude)); 

       } 
      }; 

      SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); 
      mapFragment.getMapAsync(onMapReadyCallback); 
      //Place model has all data about Location selected from search box 
     } 

     @Override 
     public void onError(Status status) { 
     } 
    }; 



    @Override 
    public void onMapReady(GoogleMap googleMap) { 

     mMap = googleMap; 
     if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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; 
     } 

     mMap.setMyLocationEnabled(true); 
     LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE); 
     Criteria criteria = new Criteria(); 
     String provider = service.getBestProvider(criteria, false); 
     Location location = getLastKnownLocation(); 
//    service.getLastKnownLocation(provider); 
     Log.e("TAG", "onResume" + location); 
     if (location != null) { 
      LatLng userLocation = new LatLng(location.getLatitude(), location.getLongitude()); 
      Log.e("TAG", "Location is " + userLocation + " " + userLocation.latitude + " " + userLocation.longitude); 
      // Add a marker in Sydney and move the camera 
      LatLng sydney = new LatLng(userLocation.latitude, userLocation.longitude); 
      mMap.addMarker(new MarkerOptions().position(sydney).title("Current Location")); 
      mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney)); 
      mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 15)); 
      Log.e("GAT","Address "+getAddress(getApplicationContext(),userLocation.latitude,userLocation.longitude)); 
     } 
    } 

    private Location getLastKnownLocation() { 
     mLocationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE); 
     List<String> providers = mLocationManager.getProviders(true); 
     Location bestLocation = null; 
     for (String provider : providers) { 
      if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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 null; 
      } 
      Location l = mLocationManager.getLastKnownLocation(provider); 
      if (l == null) { 
       continue; 
      } 
      if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) { 
       // Found best last known location: %s", l); 
       bestLocation = l; 
      } 
     } 
     return bestLocation; 
    } 

    public String getAddress(Context context, double lat, double lng) { 
     Geocoder geocoder = new Geocoder(context, Locale.getDefault()); 
     try { 
      List<android.location.Address> addresses = geocoder.getFromLocation(lat, lng, 1); 
      android.location.Address obj = addresses.get(0); 

      /*String add = obj.getAddressLine(0); 
      add = add + "\n" + obj.getCountryName(); 
      add = add + "\n" + obj.getCountryCode(); 
      add = add + "\n" + obj.getAdminArea(); 
      add = add + "\n" + obj.getPostalCode(); 
      add = add + "\n" + obj.getSubAdminArea(); 
      add = add + "\n" + obj.getLocality(); 
      add = add + "\n" + obj.getSubThoroughfare();*/ 

      String add = obj.getAddressLine(0)+","+obj.getPostalCode()+" "+obj.getAdminArea()+" "+obj.getCountryCode(); 

      return add; 
     } catch (IOException e) { 
      e.printStackTrace(); 
      Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show(); 
      return null; 
     } 
    } 
} 
+0

你確定你的代碼到達了mapFragment.getMapAsyn(this)調用嗎?您是否嘗試在調試模式下單步執行代碼? – Tamwe

回答

0

我還沒有嘗試過,但嘗試創建onMapReady()onConnected(),加buildGoogleApiClient()調用從onCreate()onMapReady()

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_map); 
    //buildGoogleApiClient(); 

    // 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); 

} 


@Override 
public void onMapReady(GoogleMap googleMap) { 
    mMap = googleMap; 

    mMap.setMyLocationEnabled(true); 

    //add this here: 
    buildGoogleApiClient(); 

    //LatLng loc = new LatLng(lat, lng); 

    //mMap.moveCamera(CameraUpdateFactory.newLatLng(loc)); 
} 

@Override 
public void onConnected(Bundle bundle) { 
    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
      mGoogleApiClient); 
    if (mLastLocation != null) { 
     lat = mLastLocation.getLatitude(); 
     lng = mLastLocation.getLongitude(); 
     mMap.moveCamera(CameraUpdateFactory.newLatLng(loc)); 
    } 
} 

您可以使用requestLocationUpdates(),並調用removeLocationUpdates()在第一位置進來

下面是一個演示應用程序,它可以幫助你瞭解如何映射API的工作原理:https://github.com/googlemaps/android-samples/tree/master/ApiDemos