JAVA百度地图的API


 
    /**
     * 通过经纬度获取地址名称
     *
     * @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;
 
    }
 
}

根据地址信息获取经纬度

import java.util.HashMap;
import java.util.Map;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import net.sf.json.JSONObject;

public class LngAndLatUtil {
public static Map<String,Double> getLngAndLat(String address){
Map<String,Double> map=new HashMap<String, Double>();
 String url = "http://api.map.baidu.com/geocoder/v2/?address="+address+"&output=json&ak=你自己的ak值";
        String json = loadJSON(url);
        JSONObject obj = JSONObject.fromObject(json);
        if(obj.get("status").toString().equals("0")){
          double lng=obj.getJSONObject("result").getJSONObject("location").getDouble("lng");
          double lat=obj.getJSONObject("result").getJSONObject("location").getDouble("lat");
          map.put("lng", lng);
          map.put("lat", lat);
          //System.out.println("经度:"+lng+"---纬度:"+lat);
        }else{
          //System.out.println("未找到相匹配的经纬度!");
        }
return map;
}
 public static String loadJSON (String url) {
        StringBuilder json = new StringBuilder();
        try {
            URL oracle = new URL(url);
            URLConnection yc = oracle.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(
                                        yc.getInputStream()));
            String inputLine = null;
            while ( (inputLine = in.readLine()) != null) {
                json.append(inputLine);
            }
            in.close();
        } catch (MalformedURLException e) {
        } catch (IOException e) {
        }
        return json.toString();
    }

}
//把代码中的ak值(红色字部分)更改为你自己的ak值,在百度地图API中注册一下就有。
//调用方式:
Map<String,Double> map=LngAndLatUtil.getLngAndLat("上海市黄浦区六合路");
System.out.println("经度:"+map.get("lng")+"---纬度:"+map.get("lat"));

百度API地址

地点检索 | 百度地图API SDK

地理编码 | 百度地图API SDK

百度开放平台后台地址

登录百度账号

简单打开百度地图APP的方法,并可以直接检索出搜索的位置

简单打开百度地图APP的方法,并可以直接检索出搜索的位置_百度地图 uid-CSDN博客

  • 6
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要在Java中调用百度地图API,你需要按照以下步骤进行操作: 1. 注册百度地图开发者账号并创建应用。 2. 选择合适的API接口,例如地理编码、路径规划、天气预报等。 3. 获取API密钥。 4. 在Java程序中使用HTTP客户端发送HTTP请求,调用对应的API接口,并将API密钥作为请求参数传递。 5. 解析API返回的JSON格式数据,提取需要的信息。 以下是一个示例代码,演示如何在Java中调用百度地图的地理编码API: ``` import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; public class BaiduMapGeocoding { public static void main(String[] args) throws Exception { // 百度地图API的URL String apiUrl = "http://api.map.baidu.com/geocoding/v3/?address=%s&output=json&ak=%s"; // 地址 String address = "北京市海淀区上地信息路5号"; // API密钥 String apiKey = "你的API密钥"; // 对地址进行URL编码 address = URLEncoder.encode(address, "UTF-8"); // 拼接URL String requestUrl = String.format(apiUrl, address, apiKey); // 发送HTTP请求 URL url = new URL(requestUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); StringBuilder response = new StringBuilder(); String line; while ((line = in.readLine()) != null) { response.append(line); } in.close(); // 解析JSON格式数据 String result = response.toString(); System.out.println(result); } } ``` 注意:此示例代码仅供参考,实际应用中需要根据需要进行修改和优化。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值