Java调用百度地图API

本实战代码将使用百度地图的接口来实现以下功能:

  1.确定输入地址的坐标

  2.两个坐标的距离

 

其他的话,还要使用百度账户申请相关的api,具体见:

http://lbsyun.baidu.com/index.php?title=webapi

 

示例代码:

import com.alibaba.fastjson.JSON;
import com.google.common.collect.ImmutableMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.fluent.Request;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Map;

/**
 * 百度地图api接口调用
 */
@Service("geocodingService")
@Transactional
public class GeocodingService {

    private static final Logger LOG = LoggerFactory.getLogger(GeocodingService.class);

    private static final Double PI = Math.PI;

    private static final Double PK = 180 / PI;

    private static final String MAP_URL= "http://api.map.baidu.com/geocoder/v2/?ak=4rcKAZKG9OIl0wDkICSLx8BA&output=json&address=";

    /**
     * 根据地址获取经纬度
     * @param address
     * @return
     */
    private Map<String,Double> getLatAndLngByAddress(String address){
        Map<String,Double> poiMap = null;
        String result = null;
        try {
            result = Request.Get(MAP_URL+ address)
                    .connectTimeout(1000).socketTimeout(1000)
                    .execute().returnContent().asString();
        } catch (IOException e) {
            LOG.error("调用百度地图API获取{}的经纬度,抛错{}",address,e);
        }
        if (StringUtils.isNotBlank(result) && "0".equals(JSON.parseObject(result).get("status") + "")){
            String lat = result.substring(result.indexOf("\"lat\":")
                    + ("\"lat\":").length(), result.indexOf("},\"precise\""));
            String lng = result.substring(result.indexOf("\"lng\":")
                    + ("\"lng\":").length(), result.indexOf(",\"lat\""));
            poiMap = ImmutableMap.of("lat",Double.parseDouble(lat),"lng",Double.parseDouble(lng));
        }
        return poiMap;
    }

    /**
     * 计算两个地址的距离(米)
     * @param address
     * @param otherAddress
     * @return
     */
    public Double getDistanceFromTwoPlaces(String address,String otherAddress){
        Double distance = null;
        if (StringUtils.isNotBlank(address) && StringUtils.isNotBlank(otherAddress)){
            address = address.trim();
            otherAddress = otherAddress.trim();
            if (address.equals(otherAddress)){
                return 0.0d;
            }
            Map pointA = getLatAndLngByAddress(address);
            Map pointB = getLatAndLngByAddress(otherAddress);
            distance = getDistanceFromTwoPoints(pointA,pointB);
        }
        return distance;
    }

    /**
     * 获取两个经纬度之间的距离(单位:米)
     * @param pointA
     * @param pointB
     * @return
     */
    private Double getDistanceFromTwoPoints(Map pointA, Map pointB) {
        Double distance = null;
        if (pointA != null && !pointA.isEmpty() && pointB != null && !pointB.isEmpty()){
            double lat_a = (double) pointA.get("lat");
            double lng_a = (double) pointA.get("lng");
            double lat_b = (double) pointB.get("lat");
            double lng_b = (double) pointB.get("lng");

            if (lat_a == lat_b && lng_a == lng_b){
                return 0.0d;
            }

            double t1 = Math.cos(lat_a / PK) * Math.cos(lng_a / PK) * Math.cos(lat_b / PK) * Math.cos(lng_b / PK);
            double t2 = Math.cos(lat_a / PK) * Math.sin(lng_a / PK) * Math.cos(lat_b / PK) * Math.sin(lng_b / PK);
            double t3 = Math.sin(lat_a / PK) * Math.sin(lat_b / PK);

            double tt = Math.acos(t1 + t2 + t3);
            distance = 6366000 * tt;
        }
        return distance;
    }
}

 

http://blog.youkuaiyun.com/u013142781/article/details/47085369

要在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); } } ``` 注意:此示例代码仅供参考,实际应用中需要根据需要进行修改和优化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值