Java基于百度API获取两地直线距离

第一步:在百度地图开放平台获取密钥
在这里插入图片描述

第二步导入jar包:主要是json的相关jar包
json-lib-2.4-jdk13.jar
commons-lang-2.6.jar
commons-beanutils-1.9.3.jar
commons-collections-3.2.1.jar
commons-logging-1.2.jar
ezmorph-1.0.6.jar
spring-core-4.3.9.RELEASE.jar

第三步:创建经纬度的类

package map;

public class LatitudeAndLongitude {
 
	private double Longitude;//经度
	private double Latitude;//纬度
	public double getLongitude() {
		return Longitude;
	}
	public void setLongitude(double lng) {
		Longitude = lng;
	}
	public double getLatitude() {
		return Latitude;
	}
	public void setLatitude(double lat) {
		Latitude = lat;
	}
	@Override
	public String toString() {
		return "LatitudeAndLongitude [Longitude=" + Longitude + ", Latitude="
				+ Latitude + "]";
	}

	
}

第三步:通过密钥获取地点的经纬度,并且计算距离


package 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 org.springframework.util.StringUtils;

import net.sf.json.JSONObject;

public class getLngAndLat {

 

    /**

     * 根据地址获得经纬度,把代码中的ak值更改为你自己的ak值

     */

    public static LatitudeAndLongitude getLngAndLat(String address) {

        LatitudeAndLongitude latAndLng = new LatitudeAndLongitude();

        String url = "http://api.map.baidu.com/geocoding/v3/?address="+address+"&output=json&ak=你自己的ak值";//GET请求
        String json = loadJSON(url);
        System.out.println(json);
        if (StringUtils.isEmpty(json))
        {
            return latAndLng;
        }

        int len = json.length();

        // 如果不是合法的json格式

        if (json.indexOf("{") != 0 || json.lastIndexOf("}") != len - 1) {
            return latAndLng;
        }

        JSONObject obj = JSONObject.fromObject(json);
        if (obj.get("status").toString().equals("0")) {
          
            double lng = obj.getJSONObject("result").getJSONObject("location").getDouble("lng");
            System.out.println(lng+"1");

            double lat = obj.getJSONObject("result").getJSONObject("location").getDouble("lat");

            latAndLng.setLatitude(lat);

            latAndLng.setLongitude(lng);
           
        }
        
        return latAndLng;

    }

    public static String loadJSON(String url) {

        StringBuilder json = new StringBuilder();

        try {

            URL urlObj = new URL(url);

            URLConnection uc = urlObj.openConnection();

            BufferedReader br = new BufferedReader(new InputStreamReader(uc.getInputStream()));

            String inputLine = null;

            while ((inputLine = br.readLine()) != null) {

                json.append(inputLine);

            }

            br.close();

        } catch (MalformedURLException e) {

        } catch (IOException e) {

        }

        return json.toString();

    }

 

    public static void main(String[] args) {
        LatitudeAndLongitude latAndLng = getLngAndLat.getLngAndLat("广东省广州市");
        LatitudeAndLongitude latAndLng2 = getLngAndLat.getLngAndLat("广西省南宁市");
        double distance=getLngAndLat.getDistance
        		(latAndLng.getLongitude(), latAndLng.getLatitude(), latAndLng2.getLongitude(), latAndLng2.getLatitude());
        System.out.println(distance);
        System.out.println("经度:" + latAndLng.getLongitude() + "---纬度:" + latAndLng.getLatitude());
        System.out.println("经度:" + latAndLng2.getLongitude() + "---纬度:" + latAndLng2.getLatitude());
    }

 

    /**

     * 计算两点之间真实距离

     * @return 千米

     */

    public static double getDistance(double longitude1, double latitude1, double longitude2, double latitude2) {

        // 维度
        double lat1 = (Math.PI / 180) * latitude1;
        double lat2 = (Math.PI / 180) * latitude2;

        // 经度
        double lon1 = (Math.PI / 180) * longitude1;
        double lon2 = (Math.PI / 180) * longitude2;

        // 地球半径
        double R = 6371;
        
        // 两点间距离 km,如果想要米的话,结果*1000就可以了
        double d = Math.acos
        (Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * Math.cos(lat2) * Math.cos(lon2 - lon1)) * R;
        return d ;
    }

 

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 可以使用Python的urllib库,先构造URL,然后通过urllib.request.urlopen函数发送请求,获取返回的数据,最后使用json.loads函数解析数据,从中获取两地距离即可,下面是实现的代码示例:import urllib.request import json# 构造URL url = 'http://api.map.baidu.com/direction/v2/driving?origin=上海&destination=深圳&ak=你的ak'# 发送请求 req = urllib.request.urlopen(url)# 获取返回的数据 data = req.read().decode('utf-8')# 解析数据 jsonData = json.loads(data)# 从中获取两地距离 distance = jsonData['result']['routes'][0]['distance']print(distance) ### 回答2: 要使用Python获取两地之间的距离,不使用API,可以通过构造百度地图URL来实现。 首先,我们需要确定两地的经纬度坐标。可以使用百度地图或其他工具获取各地的经纬度信息。 然后,我们可以通过拼接URL参数的方式构造百度地图URL。其中包括以下参数: 1. 源地点坐标(origin):指定起始地点的经纬度坐标。 2. 目的地坐标(destination):指定目的地点的经纬度坐标。 3. 输出格式(output):指定返回结果的格式,可以选择xml或json格式。 4. 百度地图开发者密钥(ak):用于授权访问百度地图。 下面是一个示例代码,展示如何构造百度地图URL并获取两地之间的距离: ```python import urllib.parse import urllib.request def get_distance(origin, destination): origin = urllib.parse.quote(origin) destination = urllib.parse.quote(destination) ak = "your_baidu_map_api_key" # 替换为你的百度地图开发者密钥 url = f"http://api.map.baidu.com/routematrix/v2/driving?output=json&origins={origin}&destinations={destination}&ak={ak}" try: response = urllib.request.urlopen(url) result = response.read().decode() # 处理返回结果,这里以json格式为例 # 解析json获取距离信息 distance = parse_result(result) return distance except urllib.error.URLError as e: print(e.reason) def parse_result(result): # 解析json获取距离信息 # 这里只提取了一个示例解析方式,实际需要根据返回结果进行相应处理 import json data = json.loads(result) distance = data["result"][0]["distance"]["text"] return distance # 调用示例 origin = "北京" destination = "上海" distance = get_distance(origin, destination) print(f"距离:{distance}") ``` 以上代码中的origin和destination是示例数据,你需要将其替换为自己想要查询的两地名称或经纬度坐标。 此代码通过构造百度地图URL并发送HTTP请求,获取两地之间的距离信息,并进行解析处理后返回结果。 ### 回答3: Python使用百度地图URL获取两地距离的方法如下: 1. 首先,我们需要引入Python的`requests`库,以便发送HTTP请求获取响应结果。 ```python import requests ``` 2. 接下来,我们可以定义一个函数,该函数接收两个地点的经纬度,并返回这两个地点之间的距离。 ```python def get_distance(point1, point2): url = f"http://api.map.baidu.com/direction/v2/routematrix?output=json&origins={point1}&destinations={point2}&ak=你的百度地图AK" response = requests.get(url) data = response.json() distance = data["result"][0]["distance"]["text"] return distance ``` 请注意,这里的`point1`和`point2`参数代表地点的经纬度信息,你需要将其替换为你所需查询的地点的经纬度。此外,`ak`参数是百度地图的开发者密钥,你需要将其替换为自己的密钥。 3. 最后,你可以调用这个函数来获取两地之间的距离。 ```python poi1 = "39.915,116.404" # 地点1的经纬度 poi2 = "31.249,121.487" # 地点2的经纬度 distance = get_distance(poi1, poi2) print(f"地点1和地点2之间的距离为:{distance}") ``` 以上代码实现了使用百度地图URL获取两地距离的功能。请注意,在实际使用时,你需要将代码中的百度地图AK替换为自己的开发者密钥,并将poi1和poi2替换为你所需查询的地点的经纬度。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值