Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách lấy thông tin đường phố (street) từ Network Provider trên Android

Giới thiệu

Lấy tên đường/phố (street name) từ vị trí mạng bằng Geocoder và phương thức address.getFeatureName() hoặc address.getThoroughfare(). Hữu ích cho ứng dụng định vị, giao hàng, check-in.

Các bước thực hiện

Bước 1: Tạo dự án

Android Studio → New Project → Empty Activity.

Bước 2: Layout (activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:gravity="center"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/text"
        android:textSize="24sp"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="16dp"
        android:gravity="center" />

</LinearLayout>

Bước 3: MainActivity.java

package com.example.myapplication;

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.appcompat.app.AppCompatActivity;
import android.widget.TextView;
import java.io.IOException;
import java.util.List;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {
    TextView textView;
    Location location;
    List<Address> addresses;
    Geocoder geocoder;

    @RequiresApi(api = Build.VERSION_CODES.P)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = findViewById(R.id.text);

        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 101);
        }

        location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        geocoder = new Geocoder(this, Locale.getDefault());
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == 101 && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            fetchStreetInfo();
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    protected void onResume() {
        super.onResume();
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        fetchStreetInfo();
    }

    private void fetchStreetInfo() {
        if (location == null) {
            textView.setText("Không có dữ liệu vị trí\nVui lòng bật GPS/Wi-Fi");
            return;
        }
        try {
            addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
            if (addresses != null && !addresses.isEmpty()) {
                Address address = addresses.get(0);
                
                StringBuilder info = new StringBuilder();
                info.append("Địa chỉ đầy đủ:\n").append(address.getAddressLine(0)).append("\n\n");
                info.append("Tên đường/địa danh (getFeatureName):\n").append(address.getFeatureName() != null ? address.getFeatureName() : "N/A").append("\n\n");
                info.append("Tên đường (getThoroughfare):\n").append(address.getThoroughfare() != null ? address.getThoroughfare() : "N/A").append("\n\n");
                info.append("Số nhà (getSubThoroughfare):\n").append(address.getSubThoroughfare() != null ? address.getSubThoroughfare() : "N/A").append("\n\n");
                info.append("Phường/Xã (getSubLocality):\n").append(address.getSubLocality() != null ? address.getSubLocality() : "N/A");
                
                textView.setText(info.toString());
            } else {
                textView.setText("Geocoder không trả về địa chỉ");
            }
        } catch (IOException e) {
            e.printStackTrace();
            textView.setText("Lỗi Geocoder: " + e.getMessage());
        }
    }
}

Bước 4: AndroidManifest.xml

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />

Các trường địa chỉ liên quan đến đường phố

Phương thứcMô tảVí dụ (Việt Nam)
getFeatureName()Tên địa danh/địa điểm nổi bật"Chợ Bến Thành", "Hồ Gươm"
getThoroughfare()Tên đường phố chính"Đường Lê Lợi", "Phố Hàng Bài"
getSubThoroughfare()Số nhà, tên ngõ/ngách"123", "Ngõ 45"
getSubLocality()Phường/Xã/Thôn"Phường Bến Nghé", "Xã Yên Hòa"
getLocality()Quận/Huyện/Thị xã"Quận 1", "Huyện Ba Vì"
getAdminArea()Tỉnh/Thành phố trực thuộc TW"Hồ Chí Minh", "Hà Nội"

Lưu ý về độ chính xác

  • Network Provider: Độ chính xác ~100-1000m, tên đường có thể sai lệch
  • GPS Provider: Độ chính xác ~5-20m, tên đường chính xác hơn
  • FusedLocationProvider: Tự động chọn provider tốt nhất (khuyến nghị)
  • Geocoder backend: Phụ thuộc vào Google Maps data, có thể thiếu dữ liệu vùng nông thôn
Khuyến nghị: Kết hợp getThoroughfare() (tên đường) + getSubThoroughfare() (số nhà) để có địa chỉ đường hoàn chỉnh. Luôn kiểm tra null trước khi sử dụng.