liujie
2023-06-12 c8638bb17163cc95e9063c358eb92cada1474102
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
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) {
        String apiKey = "AIzaSyBBW0XxW1FK7IXmmS7KFtAjX3o99eFPsss";
 
        // 创建GeoApiContext实例
        GeoApiContext context = new GeoApiContext.Builder()
                .apiKey(apiKey)
                .build();
 
        // 设置邮政编码
        String zipcode = administrativeCode;
 
        try {
            // 发起逆地理编码请求
            GeocodingResult[] results = GeocodingApi.geocode(context, zipcode).await();
 
            // 提取结果
            if (results.length > 0) {
                String formattedAddress = results[0].formattedAddress;
                System.out.println("地址:" + formattedAddress);
                return formattedAddress;
            } else {
                System.out.println("未找到地址");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    private static String getComponent(AddressComponent[] components, String type) {
        for (AddressComponent component : components) {
            if (component.types[0].equals(type)) {
                return component.longName;
            }
        }
        return null;
    }
}