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

Posted

技术标签:

【中文标题】如何获取用户的当前城市?【英文标题】:How to get a user's current city? 【发布时间】:2017-01-03 10:56:58 【问题描述】:

我想通过我的 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_
    android:layout_
    android:orientation="vertical">


    <Button
        android:id="@+id/button"
        android:layout_
        android:layout_
        android:text="Button"/>

    <TextView
        android:id="@+id/textView"
        android:layout_
        android:layout_/>
</LinearLayout>

【问题讨论】:

mLocationManager.getLastKnownLocation() 返回上次缓存的位置,在您需要提供回调的地方使用mLocationManager.requestLocationUpdates(),在该回调中您将收到最新的位置。 @Drickuss Merguez 删除了我的答案。我在这里不做编码工作。我们可以展示你想做的事情,你需要自己尝试:) 【参考方案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";
                


            

【讨论】:

@Drickuss Merguez 如果您需要帮助,请联系我 请查看***.com/questions/41445485/get-the-users-current-city/… @Drickuss Merguez 你需要答案吗? 拜托!【参考方案2】:

参考链接

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

【讨论】:

【参考方案3】:
        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();
    

【讨论】:

以上是关于如何获取用户的当前城市?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Android 中使用 gps 获取当前位置(街道、城市等)

微搭低代码小程序中获取当前城市信息

微搭低代码小程序中获取当前城市信息

如何获得当前职位的城市名称?

如何使用 Geoip 在 NodeJs 上获取当前城市名称

如何在不使用 GPS 的情况下获取 Android 设备的当前城市名称?