Java实战项目-批量获取地址间距离工具,支持中转站

Posted 秋9

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java实战项目-批量获取地址间距离工具,支持中转站相关的知识,希望对你有一定的参考价值。

目录

1获取两个地址间距离

2起始点、中转点、终点距离实现

3导出Excel文件

4封装成客户端工具


1获取两个地址间距离

获取两个地址间距离,实现方式比较多,例如基于百度地图api,高德地图api,下面基于高德地图api实现,代码如下:

    private static String getLonLat(String address)throws Exception{
//返回输入地址address的经纬度信息, 格式是 经度,纬度
        String address2 = URLEncoder.encode(address,"UTF-8");
        String queryUrl = "http://restapi.amap.com/v3/geocode/geo?key=aba6ce2149823adf738cdbe6fbb&address="+address2;

        String queryResult = getResponse(queryUrl); //高德接品返回的是JSON格式的字符串
       // System.out.println(address+"//"+queryResult);
        JSONObject jo = new JSONObject().fromObject(queryResult);

        JSONArray ja = jo.getJSONArray("geocodes");


        return new JSONObject().fromObject(ja.getString(0)).get("location").toString();

    }

    private static Long getDistance(String startLonLat, String endLonLat){
//返回起始地startAddr与目的地endAddr之间的距离,单位:米

        Long result = new Long(0);

        String queryUrl = "http://restapi.amap.com/v3/distance?key=aba6ce2149823adf738cdbe6fbb&origins="+startLonLat+"&destination="+endLonLat;

        String queryResult = getResponse(queryUrl);

        JSONObject jo = new JSONObject().fromObject(queryResult);

        JSONArray ja = jo.getJSONArray("results");

        result = Long.parseLong(new JSONObject().fromObject(ja.getString(0)).get("distance").toString());

        return result;


    }

    private static String getResponse(String serverUrl){

        StringBuffer result = new StringBuffer();

        try {
            URL url = new URL(serverUrl);

            URLConnection conn = url.openConnection();

            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));

            String line;

            while((line = in.readLine()) != null){
                result.append(line);

            }

            in.close();

        } catch (MalformedURLException e) {
            e.printStackTrace();

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

        }

        return result.toString();

    }

2起始点、中转点、终点距离实现

距离支持中转站,代码如下:

    public static Map<String,String> getDis(String start, String middle, String end){
        Map<String,String> map=new Hashtable<String,String>();
        map.put("start",start);
        if(middle!=null){
            map.put("middle",middle);
        }
        map.put("end",end);
        if(start==null||"".equals(start.trim())){
            map.put("distance","起点不能为空");
            return map;
        }
        if(end==null||"".equals(end.trim())){
            map.put("distance","终点不能为空");
            return map;
        }
        Long dis=0l;
        try {
            if(middle==null||"".equals(middle.trim())){//没有中转点
                String startLonLat = getLonLat(start);
                String endLonLat = getLonLat(end);
                dis = getDistance(startLonLat, endLonLat);
                map.put("middle","");
                map.put("distance",dis+"");
            }else{//有中转点
                String startLonLat = getLonLat(start);
                String middleLonLat = getLonLat(middle);
                String endLonLat = getLonLat(end);
                dis = getDistance(startLonLat, middleLonLat);
                dis =dis+ getDistance(middleLonLat, endLonLat);
                map.put("distance",dis+"");
            }

        }catch (Exception e){
            //e.printStackTrace();
            map.put("distance","获取失败");
        }
        //System.out.println(dis);
        return map;
    }

3导出Excel文件

导出Excel文件的默认如下,共四列,包含起始点,途径点,终点以及距离

起始点途径点终点起点到终点距离(米)
北京 石家庄 
北京天津石家庄 
浙江省杭州市西湖区 石家庄藁城市 

直接上代码

	public void exportExcel(List<Map<String,String>> resultlist,String exportPath)throws Exception{
		ExportData2Excel excel=new ExportData2Excel();
		HSSFWorkbook workbook = excel.generateWorkbook(resultlist);
		File xlsFile = new File(exportPath);
		if(!xlsFile.exists()){
			xlsFile.createNewFile();
		}
		FileOutputStream xlsStream = new FileOutputStream(xlsFile);
		workbook.write(xlsStream);

		xlsStream.close();
		xlsStream.flush();
	}
	public HSSFWorkbook generateWorkbook(List<Map<String,String>> orderList)
			throws Exception {
		// 声明一个工作薄
		HSSFWorkbook wb = new HSSFWorkbook();
		// 声明一个单子并命名
		HSSFSheet sheet = wb.createSheet("sheet1");
		// 冻结标题(width * height)
		// sheet.createFreezePane(15, 1);
		// 给单子名称一个长度
		sheet.setDefaultColumnWidth((short) 15);
		// 生成一个样式
		HSSFCellStyle style = wb.createCellStyle();
		// 设置表头颜色
		HSSFFont font = wb.createFont();
		font.setColor(HSSFColor.BLUE.index);
		style.setFont(font);
		// 水平布局 居中
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		// 上下居中
		style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
		// 不锁定
		style.setLocked(false);
		// 设置边框
		style.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 下边框
		style.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 左边框
		style.setBorderTop(HSSFCellStyle.BORDER_THIN);// 上边框
		style.setBorderRight(HSSFCellStyle.BORDER_THIN);// 右边框
		// 创建第一行(也可以称为表头)
		HSSFRow row = sheet.createRow(0);
		// 样式字体居中
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		this.createExcelTitle(row, style);
		int k = 0;
		int orderSize = orderList == null ? 0 : orderList.size();
		for (int i = 0; i < orderSize; i++) {
			k++;
			row = sheet.createRow(k);
			this.addExcelContent(row, orderList.get(i));
			// row.createCell((short) 1).setCellValue(new
			// HSSFRichTextString(StringUtil.isNullObject(orderList.get(i).get("orderId")+"")));
			// System.out.println(orderList.get(i));
		}
		return wb;
	}

	/**
	 * 
	 * 功能描述:创建工单title.
	 * 
	 */
	private void createExcelTitle(HSSFRow row, HSSFCellStyle style) {
		String[] titles = { "起始点","途径点","终点","起点到终点距离(米)" };
		for (int i = 0; i < titles.length; i++) {
			String title = titles[i];
			// 给表头第一行一次创建单元格
			HSSFCell cell = row.createCell((short) i);
			cell.setCellValue(title);
			cell.setCellStyle(style);
		}
	}


	private void addExcelContent(HSSFRow row, Map<String,String> pageData) {
		String[] fields = { "start","middle", "end" ,"distance"};
		for (int i = 0; i < fields.length; i++) {
			String field = fields[i];
			row.createCell((short) i).setCellValue(
					new HSSFRichTextString(pageData
							.get(field) + ""));
		}
	}

4封装成客户端工具

下面就用JFrame封装,封装后的界面如下:

代码如下

public class AreaUI extends JFrame {
    private JButton btn;
    private JPanel contentPane;    //内容面板
    private JTextField textField;    //文本框
    JButton okBtn ;//地址获取按钮
    public AreaUI() {
        setTitle("批量获取地址间距离工具");    //设置窗体的标题
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    //设置窗体退出时操作
        setBounds(100, 100, 800, 400);    //设置窗体位置和大小

        contentPane = new JPanel();    //创建内容面板
        contentPane.setBorder(new EmptyBorder(100, 5, 5, 5));    //设置面板的边框
        contentPane.setLayout(new BorderLayout(0, 0));    //设置内容面板为边界布局
        setContentPane(contentPane);    //应用内容面板
        JPanel panel1 = new JPanel();    //新建面板用于保存文本框
        panel1.setBounds(5, 100, 800, 100);
        contentPane.add(panel1, BorderLayout.NORTH);    //将面板放置在边界布局的北部
        textField = new JTextField();    //新建文本框
        panel1.add(textField);    //将文本框增加到面板中
        textField.setPreferredSize(new Dimension(400, 40));
        final JButton btn = new JButton("选择文件");
        btn.setPreferredSize(new Dimension(100, 40));
        panel1.add(btn);
        JPanel panel2 = new JPanel();    //新建面板用于保存按钮
        contentPane.add(panel2, BorderLayout.CENTER);    //将面板放置在边界布局的中央
        okBtn = new JButton("批量获取");

        okBtn.setPreferredSize(new Dimension(100, 40));
        panel2.add(okBtn);
        setVisible(true);
        btn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                //按钮点击事件
                JFileChooser chooser = new JFileChooser();             //设置选择器
                chooser.setMultiSelectionEnabled(true);             //设为多选
                int returnVal = chooser.showOpenDialog(btn);        //是否打开文件选择框
                if (returnVal == JFileChooser.APPROVE_OPTION) {          //如果符合文件类型
                    String filepath = chooser.getSelectedFile().getAbsolutePath();      //获取绝对路径
                    //System.out.println(filepath);
                    textField.setText(filepath);
                }
            }
        });


        /* 确定点击 */
        okBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                String filepath = textField.getText();
                if ("".equals(filepath) || filepath == null) {
                    JOptionPane.showMessageDialog(getContentPane(), "请先选择文件","警告", JOptionPane.WARNING_MESSAGE);
                    return;
                }

                String suffix = filepath.substring(filepath.lastIndexOf(".") + 1);
                if (!(suffix.equals("xlsx") || (suffix.equals("xls")))) {
                    JOptionPane.showMessageDialog(getContentPane(), "请选择Excel文件","警告", JOptionPane.WARNING_MESSAGE);
                    return;
                }
                File exitFile=new File(filepath);
                if(!exitFile.exists()){
                    JOptionPane.showMessageDialog(getContentPane(), "文件地址不存在","警告", JOptionPane.WARNING_MESSAGE);
                    return;
                }
                try {
                    List<DistanceVO> list =openFile(filepath); /* 打开文件 */
                    if(list==null||list.isEmpty()){
                        JOptionPane.showMessageDialog(getContentPane(), "解析Excel失败","警告", JOptionPane.WARNING_MESSAGE);
                        return;
                    }

                    List<Map<String,String>> pageDataList=new ArrayList<Map<String,String>>();
                    int listSize=list.size();
                    int listIndexNum=0;
                    System.out.println("共需要获取"+listSize+"个");
                    for(DistanceVO distanceVO:list){
                        listIndexNum++;
                        Map<String,String> map=DistanceUtil.getDis(distanceVO.getStart(),distanceVO.getMiddle(),distanceVO.getEnd());
                        pageDataList.add(map);
                        if(listIndexNum%100==0){
                            System.out.println(getCurTime()+"使劲获取中,共"+listSize+"已获取"+listIndexNum+"个");
                        }
                    }
                    System.out.println("地址已全部获取完成……");
                    ExportData2Excel exportData2Excel=new ExportData2Excel();
                    String exportPath="";
                    if (suffix.equals("xlsx")){
                        exportPath=filepath.replaceAll(".xlsx","转化后.xls");
                    }else if(suffix.equals("xls")){
                        exportPath=filepath.replaceAll(".xls","转化后.xls");
                    }
                    exportData2Excel.exportExcel(pageDataList,exportPath);

                    JOptionPane.showMessageDialog(getContentPane(), "获取后文件保存地址:"+exportPath,"提示", JOptionPane.INFORMATION_MESSAGE);
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
                okBtn.setText("地址获取");
            }

        });
    }

    /* 打开对应的Excel文件 */
    public List<DistanceVO> openFile(String filepath) throws IOException {
        FileInputStream fileInputStream = new FileInputStream(new File(filepath));
        XSSFWorkbook workbook = new XSSFWorkbook(fileInputStream);
        List<DistanceVO> list= queryRows(workbook);
        if(fileInputStream!=null){
            fileInputStream.close();
        }
        return list;
    }

    /* 检索需要信息 */
    public List<DistanceVO> queryRows(XSSFWorkbook workbook) {
        List<DistanceVO> list = new ArrayList<>();
        XSSFSheet sheet = workbook.getSheetAt(0);
        for (int i = 1; i <= sheet.getLastRowNum(); i++) {
            //System.out.println(sheet.getRow(i).getCell(0).getStringCellValue());
            DistanceVO vo=new DistanceVO();
            vo.setStart(sheet.getRow(i).getCell(0).getStringCellValue());
            try {
                vo.setMiddle(sheet.getRow(i).getCell(1).getStringCellValue());
            }catch (Exception e){}
            vo.setEnd(sheet.getRow(i).getCell(2).getStringCellValue());
            list.add(vo);
        }
        return list;
    }

    private String getCurTime(){
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
       return df.format(new Date());
    }
    public static void main(String[] args) {
        AreaUI ui= new AreaUI();
    }

以上是关于Java实战项目-批量获取地址间距离工具,支持中转站的主要内容,如果未能解决你的问题,请参考以下文章

java两点间距离公式

实战小项目python开发自动化运维工具--批量操作主机

c# 计算地球上两点间距离

Java获取真实的IP地址

java工具类 六 根据经纬度计算距离

将文本创建为位图的工具(消除锯齿文本、自定义间距、透明背景)