在ideal中用java计算距离
由于常常需要使用pycharm。但是又必须运行计算距离的程序,所以考虑在ideal中运行,方法如下:
import java.io.*;
import java.math.BigDecimal;
import java.sql.*;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import java.util.concurrent.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
public class temp_cxsx {
public static void main(String []args){
//数据库连接
String URL="jdbc:mysql://8.140.178.29:3306/cxsx?createDatabaseIfNotExist=true&useUnicode=true&characterEncoding=utf8";
String NAME="cxsx";//登录名
String PASSWORD="cxsx123";//密码
Connection con = null;
Statement statement = null;
ResultSet res = null;
String path="C:\\Users\\小风淅淅\\IdeaProjects\\PatternClassification\\src\\lab1\\position.txt";
try {
ArrayList<String> positions=readF1(path);
Class.forName("com.mysql.jdbc.Driver");
System.out.println("成功加载驱动程序");
con = DriverManager.getConnection(URL,NAME,PASSWORD);
statement = con.createStatement();
System.out.println("获取数据库连接成功!");
String sql="select * from hotel_jinan";
PreparedStatement pre = con.prepareStatement(sql);
//得到所有酒店
ResultSet re = pre.executeQuery();
String start;
String end;
float score=0;
int comments=0;
float price=0;
String type="";
//计算每个景点到每家酒店的距离
for (int i =0 ;i<positions.size();i++){
start = positions.get(i);
int k=0;
while(re.next()){
System.out.println(start);
//计算距离
try {
end = re.getString(1);
System.out.println(end);
String startLonLat = getLonLat(start);
String endLonLat = getLonLat(end);
ExecutorService executor = Executors.newSingleThreadExecutor();
FutureTask<Integer> future =
new FutureTask<Integer>(new Callable<Integer>() {//使用Callable接口作为构造参数
public Integer call() {
//真正的任务在这里执行,这里的返回值类型为String,可以为任意类型
try {
int dis = getDistance(startLonLat, endLonLat);
return dis;
}
catch (Exception e){
return 9999;
}
}});
executor.execute(future);
int dis=9999;
try {
dis = future.get(3000, TimeUnit.MILLISECONDS); //取得结果,同时设置超时执行时间为5秒。同样可以用future.get(),不设置执行超时时间取得结果
} catch (InterruptedException e) {
} catch (ExecutionException e) {
} catch (TimeoutException e) {
} finally {
executor.shutdown();
}
BigDecimal a = new BigDecimal(dis);
BigDecimal b = new BigDecimal(1000);
BigDecimal c = a.divide(b);
double dist = c.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
if(dist>999){
continue;
}
String sql_1="insert into distance(position,hotel,distance,score, comments,price,type) " +
"values(\""+start+"\",\""+end+"\",\""+dist+"\",\""
+score+"\",\""+comments+"\",\""+price+"\",\""
+type+"\")";
PreparedStatement pr = con.prepareStatement(sql);
int d=pr.executeUpdate(sql_1);
System.out.println(k);
System.out.println(dist);
k++;
}
catch (Exception e){
continue;
}
}
}
}
catch(ClassNotFoundException e)
{
System.out.println(e);
System.out.println("驱动程序类找不到");
}
catch(SQLException e1)
{
System.out.println(e1);
}
catch (Exception e){
System.out.println(e);
}
}
private static String getLonLat(String address){
//返回输入地址address的经纬度信息, 格式是 经度,纬度
String queryUrl = "http://restapi.amap.com/v3/geocode/geo?key=5a6ed75cb0f9bd6556fa8382ca14bfee&address="+address;
String queryResult = getResponse(queryUrl); //高德接品返回的是JSON格式的字符串
JSONObject jo = new JSONObject().fromObject(queryResult);
JSONArray ja = jo.getJSONArray("geocodes");
return new JSONObject().fromObject(ja.getString(0)).get("location").toString();
}
private static Integer getDistance(String startLonLat, String endLonLat){
//返回起始地startAddr与目的地endAddr之间的距离,单位:米
int result = 0;
String queryUrl = "http://restapi.amap.com/v3/distance?key=5a6ed75cb0f9bd6556fa8382ca14bfee&origins="+startLonLat+"&destination="+endLonLat;
String queryResult = getResponse(queryUrl);
JSONObject jo = new JSONObject().fromObject(queryResult);
JSONArray ja = jo.getJSONArray("results");
result = Integer.parseInt(new JSONObject().fromObject(ja.getString(0)).get("distance").toString());
return result;
// return queryResult;
}
private static String getResponse(String serverUrl){
//用JAVA发起http请求,并返回json格式的结果
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();
}
public static ArrayList<String> readF1(String filePath) throws IOException {
ArrayList<String> positions = new ArrayList<String>();
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(filePath)));
for (String line = br.readLine(); line != null; line = br.readLine()) {
positions.add(line);
// System.out.println(line);
}
br.close();
return positions;
}
}