2016-11-12 5 views
0

ユーザーが場所の名前を入力すると、さまざまな場所が示唆されるようにマップアクティビティを作成しました。ユーザーが選択すると、マップは選択した場所に配置されます。私は同じもののために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

私はそれを試してみましたが、onConnected()onMapReady()を作成しようとしていない、あなたがrequestLocationUpdates()を使用することができます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)); 
    } 
} 

にbuildGoogleApiClient()の呼び出しを追加し、removeLocationUpdates()を呼び出すときに最初の場所入ってくる。

マップapiの仕組みを理解するのに役立つデモアプリ:https://github.com/googlemaps/android-samples/tree/master/ApiDemos

関連する問題