如何获取用户当前的城市?

时间:2017-01-03 10:56:58

标签: java android android-studio geolocation

我想通过Android应用程序获取用户的当前位置。我一直看到如果出现任何问题从手机的GPS获取位置应该显示的错误信息。你能告诉我我的代码有什么问题吗?

MainActivity.java:

package com.example.apple.project;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {

    private static final int MY_PERMISSIONS_REQUEST_LOCATION = 1;

    TextView textView;

    Button button;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = (TextView) findViewById(R.id.textView);

        button = (Button) findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (ContextCompat.checkSelfPermission(MainActivity.this,
                        Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                            Manifest.permission.ACCESS_COARSE_LOCATION)) {
                        ActivityCompat.requestPermissions(MainActivity.this,
                                new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION);
                    } else {
                        ActivityCompat.requestPermissions(MainActivity.this,
                                new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION);
                    }
                } else {
                    LocationManager mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
                    Location location = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    try {
                        textView.setText(hereLocation(location.getLatitude(), location.getLongitude()));
                    } catch (Exception e) {
                        Toast.makeText(getApplicationContext(), "Not found!",
                                Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_LOCATION: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if (ContextCompat.checkSelfPermission(MainActivity.this,
                            Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {

                        LocationManager mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
                        Location location = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        try {
                            textView.setText(hereLocation(location.getLatitude(), location.getLongitude()));
                        } catch (Exception e) {
                            Toast.makeText(getApplicationContext(), "Not found!",
                                    Toast.LENGTH_SHORT).show();
                        }

                    }
                } else {
                    Toast.makeText(MainActivity.this, "No permission granted!", Toast.LENGTH_SHORT).show();
                }
                return;
            }
        }
    }

    public String hereLocation(double lat, double lng) {
        String cur_city_name = "";

        Geocoder gcd = new Geocoder(MainActivity.this,
                Locale.getDefault());
        List<Address> addresses;
        try {
            addresses = gcd.getFromLocation(lat, lng, 1);
            if (addresses.size() > 0)
                cur_city_name = addresses.get(0).getLocality();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Toast.makeText(this, "" + cur_city_name, Toast.LENGTH_SHORT).show();
        return cur_city_name;
    }


}

activity_main.xml中:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout        
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">


    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button"/>

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
</LinearLayout>

3 个答案:

答案 0 :(得分:1)

试试这个完美无缺的

 public String getAddress(double lats, double lons) {

                Geocoder geocoder;
                double lat = lats;
                double lon = lons;
                geocoder = new Geocoder(YourActivityName.this, Locale.getDefault());
                List<android.location.Address> addresses = null;
                try {
                    addresses = geocoder.getFromLocation(lat, lon, 1);
                } catch (IOException e) {

                    e.printStackTrace();
                }

                if (addresses != null) {

                    String address = addresses.get(0).getAddressLine(0); 
                    String city = addresses.get(0).getLocality();
                    String state = addresses.get(0).getAdminArea();
                    String country = addresses.get(0).getCountryName();
                    String postalCode = addresses.get(0).getPostalCode();
                    String knownName = addresses.get(0).getFeatureName(); 

                    return address;
                } else {
                    return "failed";
                }


            }

答案 1 :(得分:0)

参考链接

How to get city name from latitude and longitude coordinates in Google Maps?

Geocoder gcd = new Geocoder(context, Locale.getDefault());
List<Address> addresses = gcd.getFromLocation(lat, lng, 1);
if (addresses.size() > 0) 
{
    System.out.println(addresses.get(0).getLocality());
}
else
{
   // do your staff
}

答案 2 :(得分:0)

        Geocoder geocoder;
    List<Address> addresses = new ArrayList<Address>();
    geocoder = new Geocoder(MapsActivity.this, Locale.getDefault());

    try {
        addresses = geocoder.getFromLocation(lati, longi, 1);
        // Here 1 represent max location result to returned, by documents it recommended 1 to 5
      //  addresses.add();
    } catch (IOException e) {
        e.printStackTrace();
    }
    if (!addresses.isEmpty()){
        address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
        city = addresses.get(0).getLocality();
        state = addresses.get(0).getAdminArea();
        country = addresses.get(0).getCountryName();
        postalCode = addresses.get(0).getPostalCode();
    }