onMapReady在android

时间:2016-11-12 09:52:16

标签: android google-maps

我已经创建了一个Map活动,我希望在用户输入地点名称时,我会在其中建议各种地方。当用户进行任何选择时,地图应位于所选位置。我已经使用了PlaceSelectionListener。虽然我能够获得纬度和经度,但地图似乎并没有定位。它需要先前设置的位置。我已在下面附上我的代码以供参考。

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;
        }
    }
}

2 个答案:

答案 0 :(得分:0)

我还没有尝试过,但是尝试创建onMapReady()onConnected(),添加从onCreate()onMapReady()的buildGoogleApiClient()调用

@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

答案 1 :(得分:0)

确保您的 Activity 扩展并实现这些类

... extends FragmentActivity implements OnMapReadyCallback

例子,看下面的代码

public class LocationPickerActivity extends FragmentActivity implements OnMapReadyCallback{