如何从地图上获取街道地址、邮政编码、国家、州?

Posted

技术标签:

【中文标题】如何从地图上获取街道地址、邮政编码、国家、州?【英文标题】:How to get the street address ,zipcode ,country ,state from map? 【发布时间】:2018-10-20 08:06:18 【问题描述】:

我正在开发一个应用程序,当使用点击图像时,应该打开谷歌地图,当地图首先打开时它显示用户的当前位置,当用户点击地图标记上的任何位置后提交它应该采取街道名称、密码(邮政编码)、州和国家,并希望这些数据自动填充到编辑框中。 我是新的安卓,所以不明白怎么做 提前致谢

【问题讨论】:

你需要一个 api 来完成它。谷歌有一个可以做到这一点的地方 api。 cloud.google.com/maps-platform 【参考方案1】:

LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());

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

    try 
        addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1); 
        String address = addresses.get(0).getAddressLine(0); 
        String city = addresses.get(0).getLocality();


     catch (IOException e) 
        e.printStackTrace();
    

请注意: location.getLatitude() = 你的纬度值, location.getLongitude() = 你的经度值。

【讨论】:

当用户点击屏幕时它会自动获取纬度和经度值? 以及如何在点击图片时打开地图? ***.com/a/33291227/9423249 使用它您将获得纬度和经度值。对于打开地图,您需要谷歌地图集成步骤。【参考方案2】:

为了实现这一点,您需要遵循一些步骤。

第一步: 添加Location Api Lib:

implementation 'com.google.android.gms:play-services-location:11.6.0'

第二步: 将元数据添加到 AndroidManifest.xml: 用您的 API 密钥替换“密钥”

    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />
    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="key"/>

第三步: 您需要一项服务和一项活动:

1.AddressListActivity.java

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.ResultReceiver;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;

public class AddressListActivity extends AppCompatActivity 

    private FusedLocationProviderClient fusedLocationClient;

    private static final int LOCATION_PERMISSION_REQUEST_CODE = 2;

    private LocationAddressResultReceiver addressResultReceiver;

    private TextView currentAddTv;

    private Location currentLocation;

    private LocationCallback locationCallback;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.current_location_address_layout);

        Toolbar tb = findViewById(R.id.toolbar);
        setSupportActionBar(tb);
        tb.setSubtitle("Current Location Address");

        addressResultReceiver = new LocationAddressResultReceiver(new Handler());

        currentAddTv = findViewById(R.id.current_address);

        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

        locationCallback = new LocationCallback() 
            @Override
            public void onLocationResult(LocationResult locationResult) 
                currentLocation = locationResult.getLocations().get(0);
                getAddress();
            ;
        ;
        startLocationUpdates();
    

    @SuppressWarnings("MissingPermission")
    private void startLocationUpdates() 
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) 
            ActivityCompat.requestPermissions(this,
                    new String[]Manifest.permission.ACCESS_FINE_LOCATION,
                    LOCATION_PERMISSION_REQUEST_CODE);
         else 
            LocationRequest locationRequest = new LocationRequest();
            locationRequest.setInterval(2000);
            locationRequest.setFastestInterval(1000);
            locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

            fusedLocationClient.requestLocationUpdates(locationRequest,
                    locationCallback,
                    null);
        
    

    @SuppressWarnings("MissingPermission")
    private void getAddress() 

        if (!Geocoder.isPresent()) 
            Toast.makeText(AddressListActivity.this,
                    "Can't find current address, ",
                    Toast.LENGTH_SHORT).show();
            return;
        

        Intent intent = new Intent(this, GetAddressIntentService.class);
        intent.putExtra("add_receiver", addressResultReceiver);
        intent.putExtra("add_location", currentLocation);
        startService(intent);
    

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) 
        switch (requestCode) 
            case LOCATION_PERMISSION_REQUEST_CODE: 
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) 
                    startLocationUpdates();
                 else 
                    Toast.makeText(this, "Location permission not granted, " +
                                    "restart the app if you want the feature",
                            Toast.LENGTH_SHORT).show();
                
                return;
            

        
    
    private class LocationAddressResultReceiver extends ResultReceiver 
        LocationAddressResultReceiver(Handler handler) 
            super(handler);
        

        @Override
        protected void onReceiveResult(int resultCode, Bundle resultData) 

            if (resultCode == 0) 
                //Last Location can be null for various reasons
                //for example the api is called first time
                //so retry till location is set
                //since intent service runs on background thread, it doesn't block main thread
                Log.d("Address", "Location null retrying");
                getAddress();
            

            if (resultCode == 1) 
                Toast.makeText(AddressListActivity.this,
                        "Address not found, " ,
                        Toast.LENGTH_SHORT).show();
            

            String currentAdd = resultData.getString("address_result");

            showResults(currentAdd);
        
    

    private void showResults(String currentAdd)
        currentAddTv.setText(currentAdd);
    


    @Override
    protected void onResume() 
        super.onResume();
        startLocationUpdates();
    

    @Override
    protected void onPause() 
        super.onPause();
        fusedLocationClient.removeLocationUpdates(locationCallback);
    

2.您的 Intent 服务为 GetAddressIntentService

import android.app.IntentService;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.os.ResultReceiver;
import android.support.annotation.Nullable;
import android.util.Log;

import java.util.List;
import java.util.Locale;

public class GetAddressIntentService extends IntentService 

    private static final String IDENTIFIER = "GetAddressIntentService";
    private ResultReceiver addressResultReceiver;

    public GetAddressIntentService() 
        super(IDENTIFIER);
    

    //handle the address request
    @Override
    protected void onHandleIntent(@Nullable Intent intent) 
        String msg = "";
        //get result receiver from intent
        addressResultReceiver = intent.getParcelableExtra("add_receiver");

        if (addressResultReceiver == null) 
            Log.e("GetAddressIntentService",
                    "No receiver, not processing the request further");
            return;
        

        Location location = intent.getParcelableExtra("add_location");

        //send no location error to results receiver
        if (location == null) 
            msg = "No location, can't go further without location";
            sendResultsToReceiver(0, msg);
            return;
        
        //call GeoCoder getFromLocation to get address
        //returns list of addresses, take first one and send info to result receiver
        Geocoder geocoder = new Geocoder(this, Locale.getDefault());
        List<Address> addresses = null;

        try 
            addresses = geocoder.getFromLocation(
                    location.getLatitude(),
                    location.getLongitude(),
                    1);
         catch (Exception ioException) 
            Log.e("", "Error in getting address for the location");
        

        if (addresses == null || addresses.size()  == 0) 
            msg = "No address found for the location";
            sendResultsToReceiver(1, msg);
         else 
            Address address = addresses.get(0);
            StringBuffer addressDetails = new StringBuffer();

            addressDetails.append(address.getFeatureName());
            addressDetails.append("\n");

            addressDetails.append(address.getThoroughfare());
            addressDetails.append("\n");

            addressDetails.append("Locality: ");
            addressDetails.append(address.getLocality());
            addressDetails.append("\n");

            addressDetails.append("County: ");
            addressDetails.append(address.getSubAdminArea());
            addressDetails.append("\n");

            addressDetails.append("State: ");
            addressDetails.append(address.getAdminArea());
            addressDetails.append("\n");

            addressDetails.append("Country: ");
            addressDetails.append(address.getCountryName());
            addressDetails.append("\n");

            addressDetails.append("Postal Code: ");
            addressDetails.append(address.getPostalCode());
            addressDetails.append("\n");

            sendResultsToReceiver(2,addressDetails.toString());
        
    
    //to send results to receiver in the source activity
    private void sendResultsToReceiver(int resultCode, String message) 
        Bundle bundle = new Bundle();
        bundle.putString("address_result", message);
        addressResultReceiver.send(resultCode, bundle);
    

3.XML 显示你的数据

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_
    android:layout_
    tools:context=".AddressListActivity">
    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_
        android:layout_
        android:background="?attr/colorPrimary"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>
    <TextView
        android:layout_
        android:layout_
        android:layout_margin="8dp"
        android:id="@+id/add_label"
        android:textAppearance="@style/TextAppearance.AppCompat.Headline"
        android:text="Current Location Address"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/toolbar"/>
    <TextView
        android:layout_
        android:layout_
        android:layout_margin="8dp"
        android:layout_marginTop="16dp"
        android:id="@+id/current_address"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        android:lines="10"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/add_label"/>
</android.support.constraint.ConstraintLayout>

更多信息,请查看this link。

【讨论】:

这里请解释一下

以上是关于如何从地图上获取街道地址、邮政编码、国家、州?的主要内容,如果未能解决你的问题,请参考以下文章

如何验证国家和州/省名称和邮政编码?

Google Map API 通过邮政编码获取地址信息,但它通过街道号响应结果

在 GMaps Directions 服务中获取街道建议(起点)

如何使用谷歌地图 API 获取阿联酋国家/地区的邮政编码区域?

如何使用意图和活动在 Xamarin Android 中插入城市、街道、邮政编码、国家/地区的联系人?

城市/州|地区/国家的邮政编码国际数据库? [关闭]