liujie
2023-05-26 786466f6accfe836160342c56cdf3415e09bcb38
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
package com.stylefeng.guns.modular.system.utils.GoogleMap;
 
import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.maps.*;
import com.google.maps.model.*;
import com.stylefeng.guns.modular.system.utils.HttpClientUtil;
import com.stylefeng.guns.modular.system.utils.HttpResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
 
import java.util.HashMap;
import java.util.Map;
 
/**
 * 谷歌地图工具类
 */
@Slf4j
@Component
public class GoogleMapUtil {
 
    private static final String key = "AIzaSyBBW0XxW1FK7IXmmS7KFtAjX3o99eFPsss";
 
    @Autowired
    private HttpClientUtil httpClientUtil;
 
 
    /**
     * 地理编码(地址获取位置坐标)
     * @param address       地址信息
     * @throws Exception
     */
    public static GeocodeVo getGeocode(String address){
        GeoApiContext context = new GeoApiContext.Builder()
                .apiKey(key)
                .build();
        GeocodingResult[] results = null;
        try{
            results =  GeocodingApi.geocode(context, address).await();
        }catch (Exception e){
            e.printStackTrace();
            log.error("地址解析经纬度失败!");
        }
        GeocodeVo vo = null;
        if(results.length > 0){
            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            System.out.println(gson.toJson(results[0].addressComponents));
 
            Geometry geometry = results[0].geometry;
            LatLng location = geometry.location;
            vo = new GeocodeVo();
            vo.setLat(location.lat);
            vo.setLng(location.lng);
        }
        context.shutdown();
        return vo;
    }
 
 
    /**
     * 逆地理编码获取地址信息
     * @param lat   纬度
     * @param lng   经度
     * @return
     * @throws Exception
     */
    public ReverseGeocodeVo getReverseGeocode(double lat, double lng) throws Exception{
        // TODO: 2022/10/22 临时用IGO跳转
//        Map<String, Object> map = new HashMap<>();
//        map.put("lat", lat);
//        map.put("lng", lng);
//        map.put("key", key);
//        HttpResult httpResult = httpClientUtil.pushHttpRequset("POST", "http://182.160.16.251:1010/base/googleMap/getReverseGeocode", map, null, "form");
//        ReverseGeocodeVo reverseGeocode = JSON.parseObject(httpResult.getData(), ReverseGeocodeVo.class);
//        return reverseGeocode;
 
        GeoApiContext context = new GeoApiContext.Builder()
                .apiKey(key)
                .build();
        GeocodingApiRequest request = GeocodingApi.reverseGeocode(context, new LatLng(lat, lng));
        GeocodingResult[] results = request.await();
        ReverseGeocodeVo vo = null;
        if(results.length > 0){
            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            System.out.println(gson.toJson(results[0].addressComponents));
 
 
            vo = new ReverseGeocodeVo();
            AddressComponent[] addressComponents = results[0].addressComponents;
            AddressComponentsVo[] addressComponentsVos = new AddressComponentsVo[addressComponents.length];
            for (int i = 0; i < addressComponents.length; i++) {
                AddressComponentsVo addressComponentsVos1 = new AddressComponentsVo();
                addressComponentsVos1.setLongName(addressComponents[i].longName);
                addressComponentsVos1.setShortName(addressComponents[i].shortName);
                addressComponentsVos[i] = addressComponentsVos1;
            }
            String address = results[0].formattedAddress;
            vo.setAddressComponentsVos(addressComponentsVos);
            vo.setAddress(address);
        }
        context.shutdown();
        return vo;
    }
 
 
    /**
     * 搜索地图获取地图结果
     * @param input
     * @return
     * @throws Exception
     */
    public FindPlaceFromTextVo findplacefromtext(String input) throws Exception{
        GeoApiContext context = new GeoApiContext.Builder()
                .apiKey(key)
                .build();
        FindPlaceFromTextRequest request = new FindPlaceFromTextRequest(context);
        request.input(input);
        request.inputType(FindPlaceFromTextRequest.InputType.TEXT_QUERY);
        FindPlaceFromText findPlaceFromText = request.await();
        PlacesSearchResult[] candidates = findPlaceFromText.candidates;
        FindPlaceFromTextVo vo = null;
        System.err.println(JSON.toJSONString(candidates));
        if(candidates.length > 0){
            vo = new FindPlaceFromTextVo();
            String formattedAddress = candidates[0].formattedAddress;
            String name = candidates[0].name;
            Geometry geometry = candidates[0].geometry;
            if(null == geometry){//没有返回结果,使用place_id继续搜索
                // [{"permanentlyClosed":false,"placeId":"ChIJy1edVzvF7zYRaOqiGTkmb6I","rating":0.0,"userRatingsTotal":0}]
                String placeId = candidates[0].placeId;
 
 
            }
            LatLng location = geometry.location;
            double lat = location.lat;
            double lng = location.lng;
 
            vo.setName(name);
            vo.setAddress(formattedAddress);
            vo.setLat(lat);
            vo.setLng(lng);
        }
        return vo;
    }
 
 
    /**
     * 模糊搜索地图内容
     * @param query
     * @return
     * @throws Exception
     */
    public FindPlaceFromTextVo textsearch(String query) throws Exception{
        // TODO: 2022/10/22 临时用IGO跳转
//        Map<String, Object> map = new HashMap<>();
//        map.put("query", query);
//        map.put("key", key);
//        HttpResult httpResult = httpClientUtil.pushHttpRequset("POST", "http://182.160.16.251:1010/base/googleMap/textsearch", map, null, "form");
//        FindPlaceFromTextVo findPlaceFromTextVo = JSON.parseObject(httpResult.getData(), FindPlaceFromTextVo.class);
//        return findPlaceFromTextVo;
 
        GeoApiContext context = new GeoApiContext.Builder()
                .apiKey(key)
                .build();
        TextSearchRequest request = new TextSearchRequest(context);
        request.query(query);
        PlacesSearchResponse placesSearchResponse = request.await();
        PlacesSearchResult[] results = placesSearchResponse.results;
        FindPlaceFromTextVo vo = null;
        System.err.println(JSON.toJSONString(results));
        if(results.length > 0){
            vo = new FindPlaceFromTextVo();
            String formattedAddress = results[0].formattedAddress;
            String name = results[0].name;
            Geometry geometry = results[0].geometry;
            LatLng location = geometry.location;
            double lat = location.lat;
            double lng = location.lng;
 
            vo.setName(name);
            vo.setAddress(formattedAddress);
            vo.setLat(lat);
            vo.setLng(lng);
        }
        return vo;
    }
 
 
    /**
     * 获取两个地点之间的预估里程和预估时间
     * @param origin        起点
     * @param destination   终点
     * @return
     * @throws Exception
     */
    public DistancematrixVo getDistancematrix(String origin, String destination) throws Exception{
        // TODO: 2022/10/22 临时用IGO跳转
//        Map<String, Object> map = new HashMap<>();
//        map.put("origin", origin);
//        map.put("destination", destination);
//        map.put("key", key);
//        HttpResult httpResult = httpClientUtil.pushHttpRequset("POST", "http://182.160.16.251:1010/base/googleMap/getDistancematrix", map, null, "form");
//        DistancematrixVo reverseGeocode = JSON.parseObject(httpResult.getData(), DistancematrixVo.class);
//        return reverseGeocode;
 
        GeoApiContext context = new GeoApiContext.Builder()
                .apiKey(key)
                .build();
        DistanceMatrixApiRequest request = DistanceMatrixApi.getDistanceMatrix(context, new String[]{origin}, new String[]{destination});
        request.mode(TravelMode.DRIVING);//出行方式(驾车)
        DistanceMatrix distanceMatrix = request.await();
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        System.out.println(gson.toJson(distanceMatrix));
        context.shutdown();
 
        DistanceMatrixElement elements = distanceMatrix.rows[0].elements[0];
        DistancematrixVo vo = new DistancematrixVo();
        vo.setDistance(elements.distance.inMeters);
        vo.setDuration(elements.duration.inSeconds);
        return vo;
    }
 
 
    /**
     * 获取两点之间的距离
     * @param sLat
     * @param sLnt
     * @param eLat
     * @param eLnt
     * @return
     * @throws Exception
     */
    public DistancematrixVo getDistancematrix(Double sLat, Double sLnt, Double eLat, Double eLnt) throws Exception{
        ReverseGeocodeVo reverseGeocode = getReverseGeocode(sLat, sLnt);
        ReverseGeocodeVo reverseGeocode1 = getReverseGeocode(eLat, eLnt);
        if(null != reverseGeocode && null != reverseGeocode1){
            String origin = reverseGeocode.getAddress();
            String destination = reverseGeocode1.getAddress();
            return getDistancematrix(origin, destination);
        }
        return null;
    }
 
 
    /**
     * 获取两地点之间的线路规划
     * @param origin        起点 要计算方向的位置ID、地址或文本纬度/经度值。目标参数的选项与原点参数的相同。
     * @param destination   终点 要计算方向的位置ID、地址或文本纬度/经度值。目标参数的选项与原点参数的相同。
     *
     */
    public void getDirections(String origin, String destination) throws Exception{
        GeoApiContext context = new GeoApiContext.Builder()
                .apiKey(key)
                .build();
        DirectionsApiRequest directions = DirectionsApi.getDirections(context, origin, destination);
        directions.mode(TravelMode.DRIVING);//出行方式(驾车)
        DirectionsResult result = directions.await();
 
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        System.out.println(gson.toJson(result));
        context.shutdown();
    }
 
 
}