首页 > 解决方案 > Weather App,如何从MapActivity获取经纬度

问题描述

这是我第一次使用stackoverflow,很抱歉我的问题。我学习java和swift只有4-5个月,所以我只是一个初学者。我正在用谷歌地图和天气活动等其他一些功能编写一个简单的应用程序。Map Activity 运行良好,Weather Activity 也运行良好,但仅使用静态纬度和经度:

asyncTask.execute("28.125696","-15.440090" ); 

如何实现 get currentLocation.getLatitude(), currentLocation.getLongitude()from MainActivityWeather 中的asyncTask.execute(...);?我想对了吗?使用当前位置数据构建天气应用程序是一种好方法吗?地图活动:

公共类 MapActivity 扩展 AppCompatActivity 实现 OnMapReadyCallback,GoogleApiClient.OnConnectionFailedListener {

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}

@Override
public void onMapReady(GoogleMap googleMap) {
    Toast.makeText(this, "Map is Ready", Toast.LENGTH_SHORT).show();
    Log.d(TAG, "onMapReady: map is ready");
    mMap = googleMap;

    if (mLocationPermissionsGranted) {
        getDeviceLocation();

        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);
        mMap.getUiSettings().setMyLocationButtonEnabled(false);
        init();
    }
}

private static final String TAG = "MapActivity";

private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
private static final String COURSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;
private static final float DEFAULT_ZOOM = 15f;
public static final LatLngBounds LAT_LNG_BOUNDS = new LatLngBounds(
      new LatLng(-40, -168), new LatLng(71, 136)
);
//widgets

private AutoCompleteTextView mSearchText;
private ImageView mGps;

//vars
private Boolean mLocationPermissionsGranted = false;
private GoogleMap mMap;
private FusedLocationProviderClient mFusedLocationProviderClient;
private PlaceAutoCompleteAdapter mPlaceAutoCompleteAdapter;
private GoogleApiClient mGoogleApiClient;
private PlaceInfo mPlace;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_map);
    mSearchText = (AutoCompleteTextView) findViewById(R.id.input_search);
    mGps = (ImageView) findViewById(R.id.ic_gps);

    getLocationPermission();

    BottomNavigationView bottomNav = findViewById(R.id.bottom_nav);
    BottomNavigationViewHelper.removeShiftMode(bottomNav);
    bottomNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()){
                case R.id.nav_menu:

                    Intent intent0 = new Intent(MapActivity.this, MainActivity.class);
                    startActivity(intent0);
                    break;

                case R.id.nav_note:
                    Intent intent1 = new Intent(MapActivity.this, MainListActivity.class);
                    startActivity(intent1);
                    break;
                case R.id.nav_map:

                    break;

                case R.id.nav_attraction:
                    Intent intent3 = new Intent(MapActivity.this, MainActivityGrid.class);
                    startActivity(intent3);
                    break;

            }
            return false;
        }
    });

}

private void init(){
    Log.d(TAG, "init: initializing");

    mGoogleApiClient = new GoogleApiClient
            .Builder(this)
            .addApi(Places.GEO_DATA_API)
            .addApi(Places.PLACE_DETECTION_API)
            .enableAutoManage(this, this)
            .build();

    mSearchText.setOnItemClickListener(mAutocompleteClickListener );

    mPlaceAutoCompleteAdapter = new PlaceAutoCompleteAdapter(this, mGoogleApiClient, LAT_LNG_BOUNDS, null);

    mSearchText.setAdapter(mPlaceAutoCompleteAdapter);

    mSearchText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
            if(actionId == EditorInfo.IME_ACTION_SEARCH
                    || actionId == EditorInfo.IME_ACTION_DONE
                    || keyEvent.getAction() == KeyEvent.ACTION_DOWN
                    || keyEvent.getAction() == KeyEvent.KEYCODE_ENTER){

                //execute our method for searching
                geoLocate();
            }

            return false;
        }
    });
    mGps.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d(TAG, "onClick: clicked gps icon");
            getDeviceLocation();

        }
    });

    hideSoftKeyboard();
}

private void geoLocate(){
    Log.d(TAG, "geoLocate: geolocating");

    String searchString = mSearchText.getText().toString();

    Geocoder geocoder = new Geocoder(MapActivity.this);
    List<Address> list = new ArrayList<>();
    try{
        list = geocoder.getFromLocationName(searchString,1);

    }catch (IOException e) {
        Log.d(TAG, "geoLocate: IOException " +e.getMessage());
    }
    if(list.size() > 0 ){
        Address address = list.get(0);
        Log.d(TAG, "geoLocate: found a location "+ address.toString());

       moveCamera(new LatLng(address.getLatitude(), address.getLongitude()), DEFAULT_ZOOM, address.getAddressLine(0));
    }
}

private void getDeviceLocation(){
    Log.d(TAG, "getDeviceLocation: getting the devices current location");

    mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);

    try{
        if(mLocationPermissionsGranted){

            final Task location = mFusedLocationProviderClient.getLastLocation();
            location.addOnCompleteListener(new OnCompleteListener() {
                @Override
                public void onComplete(@NonNull Task task) {
                    if(task.isSuccessful()&& task.getResult() != null){
                        Log.d(TAG, "onComplete: found location!");
                        Location currentLocation = (Location) task.getResult();

                        moveCamera(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()),
                                DEFAULT_ZOOM, "My location");

                    }else{
                        Log.d(TAG, "onComplete: current location is null");
                        Toast.makeText(MapActivity.this, "unable to get current location", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
    }catch (SecurityException e){
        Log.e(TAG, "getDeviceLocation: SecurityException: " + e.getMessage() );
    }
}

private void moveCamera(LatLng latLng, float zoom, String title){
    Log.d(TAG, "moveCamera: moving the camera to: lat: " + latLng.latitude + ", lng: " + latLng.longitude );
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));

    if(!title.equals("My location")){
        MarkerOptions options = new MarkerOptions().position(latLng).title(title);
        mMap.addMarker(options);
    }
    hideSoftKeyboard();

}

private void initMap(){
    Log.d(TAG, "initMap: initializing map");
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

    mapFragment.getMapAsync(MapActivity.this);
}

private void getLocationPermission(){
    Log.d(TAG, "getLocationPermission: getting location permissions");
    String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION};

    if(ContextCompat.checkSelfPermission(this.getApplicationContext(),
            FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
        if(ContextCompat.checkSelfPermission(this.getApplicationContext(),
                COURSE_LOCATION) == PackageManager.PERMISSION_GRANTED){
            mLocationPermissionsGranted = true;
            initMap();
        }else{
            ActivityCompat.requestPermissions(this,
                    permissions,
                    LOCATION_PERMISSION_REQUEST_CODE);
        }
    }else{
        ActivityCompat.requestPermissions(this,
                permissions,
                LOCATION_PERMISSION_REQUEST_CODE);
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    Log.d(TAG, "onRequestPermissionsResult: called.");
    mLocationPermissionsGranted = false;

    switch(requestCode){
        case LOCATION_PERMISSION_REQUEST_CODE:{
            if(grantResults.length > 0){
                for(int i = 0; i < grantResults.length; i++){
                    if(grantResults[i] != PackageManager.PERMISSION_GRANTED){
                        mLocationPermissionsGranted = false;
                        Log.d(TAG, "onRequestPermissionsResult: permission failed");
                        return;
                    }
                }
                Log.d(TAG, "onRequestPermissionsResult: permission granted");
                mLocationPermissionsGranted = true;
                //initialize our map
                initMap();
            }
        }
    }
}

私人无效 hideSoftKeyboard(){ this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); }

private AdapterView.OnItemClickListener mAutocompleteClickListener = new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        hideSoftKeyboard();

        final AutocompletePrediction item = mPlaceAutoCompleteAdapter.getItem(i);
        final String placeId = item.getPlaceId();

        PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi
                .getPlaceById(mGoogleApiClient, placeId);
        placeResult.setResultCallback(mUpdatePlaceDetailsCallback);
    }
};
private ResultCallback<PlaceBuffer> mUpdatePlaceDetailsCallback = new ResultCallback<PlaceBuffer>() {
    @Override
    public void onResult(@NonNull PlaceBuffer places) {
        if (!places.getStatus().isSuccess()) {
            Log.d(TAG, "onResult: Place query did not mplete successfully" + places.getStatus().toString());
            places.release();
            return;
        }
        final Place place = places.get(0);
        try{
            mPlace = new PlaceInfo();
            mPlace.setName(place.getName().toString());
            Log.d(TAG, "onResult: name: " + place.getName());
            mPlace.setAddress(place.getAddress().toString());
            Log.d(TAG, "onResult: address: " + place.getAddress());
            mPlace.setAttributions(place.getAttributions().toString());
            Log.d(TAG, "onResult: attributions: " + place.getAttributions());
            mPlace.setId(place.getId());
            Log.d(TAG, "onResult: id:" + place.getId());
            mPlace.setLatlng(place.getLatLng());
            Log.d(TAG, "onResult: latlng: " + place.getLatLng());
            mPlace.setRating(place.getRating());
            Log.d(TAG, "onResult: rating: " + place.getRating());
            mPlace.setPhoneNumber(place.getPhoneNumber().toString());
            Log.d(TAG, "onResult: phone number: " + place.getPhoneNumber());
            mPlace.setWebsiteUri(place.getWebsiteUri());
            Log.d(TAG, "onResult: website uri: " + place.getWebsiteUri());

            Log.d(TAG, "onResult: place: " + mPlace.toString());
        }catch (NullPointerException e){
            Log.e(TAG, "onResult: NullPointerException: " + e.getMessage() );
        }

        moveCamera(new LatLng(place.getViewport().getCenter().latitude,
                place.getViewport().getCenter().longitude), DEFAULT_ZOOM, mPlace.getName());

        places.release();
    }

};}

Wheather Activities:

public class MainActivityWeather extends AppCompatActivity {

private static final String TAG = "WeatherActivity";

TextView cityField, detailsField, currentTemperatureField, humidity_field, pressure_field, weatherIcon, updatedField;

Typeface weatherFont;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

// getSupportActionBar().hide(); setContentView(R.layout.activity_main_weather);

weatherFont = Typeface.createFromAsset(getApplicationContext().getAssets(), "fonts/weathericons-regular-webfont.ttf"); cityField = (TextView)findViewById(R.id.city_field); updatedField = (TextView)findViewById(R.id.updated_field); detailsField = (TextView)findViewById(R.id.details_field); currentTemperatureField = (TextView)findViewById(R.id.current_temperature_field); humidity_field = (TextView)findViewById(R.id.humidity_field); pressure_field = (TextView)findViewById(R.id.pressure_field); weatherIcon = (TextView)findViewById(R.id.weather_icon); weatherIcon.setTypeface(weatherFont); Function.placeIdTask asyncTask =new Function.placeIdTask(new Function.AsyncResponse() { public void processFinish(String weather_city, String weather_description, String weather_temperature, String weather_humidity, String weather_pressure, String weather_updatedOn, String weather_iconText, String sun_rise) { cityField.setText(weather_city); updatedField.setText(weather_updatedOn); detailsField.setText(weather_description); currentTemperatureField.setText(weather_temperature); humidity_field.setText("Humidity: "+weather_humidity); pressure_field.setText("Pressure: "+weather_pressure); weatherIcon.setText(Html.fromHtml(weather_iconText)); } }); asyncTask.execute( ); // asyncTask.execute("Latitude", "Longitude") }}

public class Function {

private static final String OPEN_WEATHER_MAP_URL = "http://api.openweathermap.org/data/2.5/weather?lat=%s&lon=%s&units=metric"; private static final String OPEN_WEATHER_MAP_API = "fdbf72863aba44b6fc7ce9e3324a689f"; public static String setWeatherIcon(int actualId, long sunrise, long sunset){ int id = actualId / 100; String icon = ""; if(actualId == 800){ long currentTime = new Date().getTime(); if(currentTime>=sunrise && currentTime<sunset) { icon = "&#xf00d;"; } else { icon = "&#xf02e;"; } } else { switch(id) { case 2 : icon = "&#xf01e;"; break; case 3 : icon = "&#xf01c;"; break; case 7 : icon = "&#xf014;"; break; case 8 : icon = "&#xf013;"; break; case 6 : icon = "&#xf01b;"; break; case 5 : icon = "&#xf019;"; break; } } return icon; } public interface AsyncResponse { void processFinish(String output1, String output2, String output3, String output4, String output5, String output6, String output7, String output8); } public static class placeIdTask extends AsyncTask<String, Void, JSONObject> { public AsyncResponse delegate = null;//Call back interface public placeIdTask(AsyncResponse asyncResponse) { delegate = asyncResponse;//Assigning call back interfacethrough constructor } @Override protected JSONObject doInBackground(String... params) { JSONObject jsonWeather = null; try { jsonWeather = getWeatherJSON(params[0], params[1]); } catch (Exception e) { Log.d("Error", "Cannot process JSON results", e); } return jsonWeather; } @Override protected void onPostExecute(JSONObject json) { try { if(json != null){ JSONObject details = json.getJSONArray("weather").getJSONObject(0); JSONObject main = json.getJSONObject("main"); DateFormat df = DateFormat.getDateTimeInstance(); String city = json.getString("name").toUpperCase(Locale.US) + ", " + json.getJSONObject("sys").getString("country"); String description = details.getString("description").toUpperCase(Locale.US); String temperature = String.format("%.2f", main.getDouble("temp"))+ "°"; String humidity = main.getString("humidity") + "%"; String pressure = main.getString("pressure") + " hPa"; String updatedOn = df.format(new Date(json.getLong("dt")*1000)); String iconText = setWeatherIcon(details.getInt("id"), json.getJSONObject("sys").getLong("sunrise") * 1000, json.getJSONObject("sys").getLong("sunset") * 1000); delegate.processFinish(city, description, temperature, humidity, pressure, updatedOn, iconText, ""+ (json.getJSONObject("sys").getLong("sunrise") * 1000)); } } catch (JSONException e) { //Log.e(LOG_TAG, "Cannot process JSON results", e); } } } public static JSONObject getWeatherJSON(String lat, String lon){ try { URL url = new URL(String.format(OPEN_WEATHER_MAP_URL, lat, lon)); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); connection.addRequestProperty("x-api-key", OPEN_WEATHER_MAP_API); BufferedReader reader = new BufferedReader( new InputStreamReader(connection.getInputStream())); StringBuffer json = new StringBuffer(1024); String tmp=""; while((tmp=reader.readLine())!=null) json.append(tmp).append("\n"); reader.close(); JSONObject data = new JSONObject(json.toString()); // This value will be 404 if the request was not // successful if(data.getInt("cod") != 200){ return null; } return data; }catch(Exception e){ return null; } }}

标签: javaandroidgps

解决方案


推荐阅读