java 百度地图获取经纬度



 

    /**
     * 通过经纬度获取地址名称
     *
     * @param latitude(维度), longitude(经度)
     * @return address(地址)
     */
    @GetMapping(value = "/getAddress")
    public Result getAddress(@RequestParam(value = "LATITUDE") String latitude,
                             @RequestParam(value = "LONGITUDE") String longitude) {
        Map<String, String> result = new HashMap<>();
        result.put("ADDRESS", MapUtil.getAddressByLatAndLng(latitude, longitude));
        return Result.buildResult(Result.Status.OK, result);
    }

    /**
     * 通过地址获取经纬度
     *
     * @param
     * @return address(地址)
     */
    @GetMapping(value = "/getLatAndLngByAddress")
    public Result getLatAndLng(@RequestParam(value = "ADDRESS") String address) {
        return Result.buildResult(Result.Status.OK, MapUtil.getLatAndLngByAddress(address));
    }

   

    //数组转集合
    private List<String> array2List(String[] strings) {
        return Arrays.asList(strings);
    }
    

    //判断两个经纬度的距离
    private static final double EARTH_RADIUS = 6378.137;//地球半径,单位千米

    //将角度转为弧度
    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }

    private static double getDistance(double lat1, double lng1, double lat2, double lng2) {
        double radLat1 = rad(lat1);
        double radLat2 = rad(lat2);
        double a = radLat1 - radLat2;
        double b = rad(lng1) - rad(lng2);

        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
                Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
        s = s * EARTH_RADIUS;
        s = Math.round(s * 1000);
        return s;

    }


}
package springboot_001.utils;

import com.google.gson.Gson;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.params.ConnRouteParams;
import org.apache.http.impl.client.DefaultHttpClient;
import springboot_001.safeguard.controller.WeLinkZBController;
import springboot_001.safeguard.entity.MapResult;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhao pan
 * @Date 16:19 2019/12/18
 * @Description
 */
public class MapUtil {
    public static final String ak = "1NKC2pNxVRKuPBdzkIrjiTAdiFE7VcyB";
    //    private static final String ak = "4IKgN0DzGVgiGtXW0hm8Z0OWsnYL7CuM";
    //    private static final String mapUrl = "172.30.68.94:8080";
    public static final String mapUrl = "api.map.baidu.com";

    public static String getAddressByLatAndLng(String latitude, String longitude) {
        StringBuffer sb = new StringBuffer();
        //创建HttpClient实例
        HttpClient client = getHttpClient();
        //创建httpGet
        HttpGet httpGet = new HttpGet("http://" + mapUrl + "/reverse_geocoding/v3/?ak=" + ak + "&output=json&coordtype=wgs84ll&location=" + latitude + "," + longitude);  //先维度(lati)后经度
        //执行
        try {
            HttpResponse response = client.execute(httpGet);
            HttpEntity entry = response.getEntity();
            if (entry != null) {
                InputStreamReader is = new InputStreamReader(entry.getContent());
                BufferedReader br = new BufferedReader(is);
                String str = null;
                while ((str = br.readLine()) != null) {
                    sb.append(str.trim());
                }
                br.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            return "地址获取失败";
        } catch (IOException e) {
            e.printStackTrace();
            return "地址获取失败";
        }
        Gson gson = new Gson();
        MapResult mapResult = gson.fromJson(sb.toString(), MapResult.class);
        if (mapResult.getResult() == null || mapResult.getResult().get("formatted_address") == null) {
            return "地址获取失败";
        }
        return mapResult.getResult().get("formatted_address").toString();
    }

    public static Map<String, Object> getLatAndLngByAddress(String address) {
        Map<String, Object> result = new HashMap<>();
        StringBuffer sb = new StringBuffer();
        //创建HttpClient实例
        HttpClient client = getHttpClient();
        //创建httpGet
        HttpGet httpGet = new HttpGet("http://" + mapUrl + "/geocoding/v3/?ak=" + ak + "&output=json&callback=showLocation&address=" + address);
        //执行
        try {
            HttpResponse response = client.execute(httpGet);
            HttpEntity entry = response.getEntity();
            if (entry != null) {
                InputStreamReader is = new InputStreamReader(entry.getContent());
                BufferedReader br = new BufferedReader(is);
                String str = null;
                while ((str = br.readLine()) != null) {
                    sb.append(str.trim());
                }
                br.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();

            return result;
        } catch (IOException e) {
            e.printStackTrace();

            return result;
        }
        Gson gson = new Gson();
        MapResult mapResult = gson.fromJson(sb.toString().replaceAll("showLocation&&showLocation\\(", "").replaceAll("\\)", ""), MapResult.class);
        if(mapResult.getResult() == null) return result;
        Map<String, Object> mapResultLocation = (Map<String, Object>) mapResult.getResult().get("location");
        result.put("LATITUDE", mapResultLocation.get("lat"));  //维度
        result.put("LONGITUDE", mapResultLocation.get("lng"));  //经度
        return result;
    }

    public static Map<String, Object> getInfoByLatAndLng(String latitude, String longitude){
        Map<String, Object> result = new HashMap<>();
        StringBuffer sb = new StringBuffer();
        //创建HttpClient实例
        HttpClient client = getHttpClient();
        //创建httpGet
        HttpGet httpGet = new HttpGet("http://" + mapUrl + "/reverse_geocoding/v3/?ak=" + ak + "&output=json&coordtype=wgs84ll&location=" + latitude + "," + longitude);  //先维度(lati)后经度
        //执行
        try {
            HttpResponse response = client.execute(httpGet);
            HttpEntity entry = response.getEntity();
            if (entry != null) {
                InputStreamReader is = new InputStreamReader(entry.getContent());
                BufferedReader br = new BufferedReader(is);
                String str = null;
                while ((str = br.readLine()) != null) {
                    sb.append(str.trim());
                }
                br.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            return result;
        } catch (IOException e) {
            e.printStackTrace();
            return result;
        }
        Gson gson = new Gson();
        MapResult mapResult = gson.fromJson(sb.toString(), MapResult.class);
        if (mapResult.getResult() == null || mapResult.getResult().get("formatted_address") == null) {
            return result;
        }
        return ( Map<String, Object>)mapResult.getResult().get("addressComponent");
    }

    //设置代理
    private static HttpClient getHttpClient() {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        String proxyHost = "openproxy.huawei.com";
        int proxyPort = 8080;
        String userName = "bwx686365";
        String password = "lmwda@1314";
        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(proxyHost, proxyPort),
                new UsernamePasswordCredentials(userName, password));
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        httpClient.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
        return httpClient;

    }

}
发布了184 篇原创文章 · 获赞 73 · 访问量 37万+

猜你喜欢

转载自blog.csdn.net/qq_32521313/article/details/103957610