liujie
2023-05-22 9f2315d92cc93f8f431805a10ea9ce3f79fa7eb2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package com.stylefeng.guns.modular.system.utils;
 
import com.google.maps.GeoApiContext;
import com.google.maps.GeocodingApi;
import com.google.maps.model.AddressComponent;
import com.google.maps.model.GeocodingResult;
 
public class AddressLookup {
    
    public static String getAddress(String administrativeCode) {
        GeoApiContext context = new GeoApiContext.Builder()
            .apiKey("AIzaSyBBW0XxW1FK7IXmmS7KFtAjX3o99eFPsss") // REPLACE WITH YOUR API KEY
            .build();
        
        GeocodingResult[] results = GeocodingApi.geocode(context, "EN " + administrativeCode).awaitIgnoreError();
        
        if (results == null || results.length == 0) {
            return null;
        }
        
        AddressComponent[] components = results[0].addressComponents;
        String province = getComponent(components, "administrative_area_level_1");
        String city = getComponent(components, "locality");
        String district = getComponent(components, "administrative_area_level_3");
        String street = getComponent(components, "route");
        String number = getComponent(components, "street_number");
        
        StringBuilder builder = new StringBuilder();
        
        if (province != null) {
            builder.append(province);
        }
        
        if (city != null && !city.equals(province)) {
            builder.append(city);
        }
        
        if (district != null && !district.equals(city)) {
            builder.append(district);
        }
        
        if (street != null) {
            builder.append(street);
        }
        
        if (number != null) {
            builder.append(number);
        }
        
        return builder.toString();
    }
    
    private static String getComponent(AddressComponent[] components, String type) {
        for (AddressComponent component : components) {
            if (component.types[0].equals(type)) {
                return component.longName;
            }
        }
        return null;
    }
}