• About Me
  • Java基礎教學
  • 部落格聯播

[jsp]利用Google Map查詢經緯度

分類: database, google, Java, javascript, opensource, prototype, 教學 時間:2010/4/26 瀏覽:3,187 瀏覽數 — 5 回應

如果手上有一堆地址清單想要知道它們的經緯度如何?要怎麼做呢?這裡介紹一個很簡單的方法,利用二個Ajax及Google Map就可以完成,一個要求地址欄位及key值(這其實可以直接全都先輸出成javascript的Array就好了),另一個接收到經緯度資料後回傳給Server做儲存(這也可以直接利用一個TextArea存放,到時再複製起來存放),而Google Map最主要的功能就是把地址轉換成經緯度。

GoogleMap3.png

做法及想法如下:

1.建立資料庫Table

需要有一個pk值、地址、經度、緯度及一個記錄是否已取得成功的註記符號,MySQL語法如下:

ps.先建立幾筆資料做測試,如下insert

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
CREATE TABLE `test`.`Address` (
  `id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
  `zip_name` VARCHAR(45) NOT NULL,
  `address` VARCHAR(500) NOT NULL,
  `latitude` VARCHAR(100),
  `longitude` VARCHAR(100),
  `flg` VARCHAR(1),
  PRIMARY KEY (`id`)
)
ENGINE = InnoDB;
 
INSERT INTO ADDRESS (zip_name,address) 
VALUES ('台中市北屯區', '崇德路130號14樓A1');
INSERT INTO ADDRESS (zip_name,address) 
VALUES ('台中市西區', '忠明南路122號');

2.建立GoogleMap

要使用GoogleMap的方法如下:

  1. 申請金鑰
  2. 建立顯示區塊
  3. <body onload>時init
  4. 建立GMap2物件
  5. 設定中心點
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<script
    src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=你申請的 key值"
    type="text/javascript"></script>
<script type="text/javascript">
function load()
{
    //取得map物件
    map = new GMap2(document.getElementById("map"));
    //增加control元件,放大縮小跟地圖種類
    map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());
    var centerX = 24.170992;
    var centerY = 120.683280;
    //設定中心點,設定完成就已經算init好了
    map.setCenter(new GLatLng(centerX, centerY), 8);
}
<body onload="load();" onunload="GUnload();">
<div id="map" style="width:500px;height:500px;float:left"></div>
</body>

3.取得Server地址及回傳經緯度

SearchLonLat.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
new Ajax.Request('getAddress.jsp', {
        method: 'get',
        asynchronous:false ,
        onSuccess: function(transport) {
          var Doc = transport.responseText;
          if(Doc=="")//代表已經沒有任何資料了
          {
              stop = true;
              return ;
          }
          //回傳值為id","地址  
          Doc = Doc +"\",\"";
          //arr[0]是id
          //arr[1]是地址
          var arr = Doc.split("\",\"");
 
        if (geocoder) 
        {
           var data = ['',''];
           //利用getLatLng方法,傳入地址,
           //callback來處理回傳的經緯度data
           geocoder.getLatLng(
           arr[1],
           function(point) {
           if (point) {        
             data = setLoLa(point);
          }
            //再把資料傳送給server要求更新,或存放起來
          new Ajax.Request('sendloglat.jsp', {
                method: 'get',
                parameters :{id:arr[0],logitude:data[0],latitude:data[1]},
                asynchronous:false ,
                onSuccess: function(transport) {
                  //這裡可以設定成功後要做什麼動作
                }
                });
         }
         );
         }
        //設定已完成動作,其它查詢可進行
        start = true;    
        }
      });

以下是取得地址及傳給WebClient-getAddress.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<%@ page language="java" contentType="text/html; charset=BIG5"
    pageEncoding="BIG5"%><%java.sql.Connection con = null;
    java.sql.Statement stat = null;
    java.sql.ResultSet rs = null;
    try
    {
        con = db.ConnectionPool.getCon();
        String sql = "select id,concat(zip_name,address) as address_data from address " +
            "where flg is null " +
            "limit 1";
        //一次取一筆未執行的資料,flg為註記是否已執行過
        stat = con.createStatement();
        rs = stat.executeQuery(sql);
        if(rs.next())
        {
            out.print(rs.getInt("id")+"\",\""+rs.getString("address_data"));
        }
    }
    catch(java.sql.SQLException e)
    {
        e.printStackTrace();
    }
    finally
    {
        try
        {
            if(rs!=null)
            {
                rs.close();
                rs=null;
            }
            if(stat!=null)
            {
                stat.close();
                stat=null;
            }
            if(con!=null)
            {
                con.close();
                con=null;
            }
        }
        catch(java.sql.SQLException e)
        {
            System.out.println("Close Error!");
        }
    }%>

以下是接受WebClient傳來的經緯度及pk值,更新資料-sendloglat.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<%@ page language="java" contentType="text/html; charset=BIG5"
    pageEncoding="BIG5"%><%java.sql.Connection con = null;
    java.sql.PreparedStatement pst = null;
 
    String id = request.getParameter("id");
    String logitude = request.getParameter("logitude");
    String latitude = request.getParameter("latitude");
    if(logitude.equals(""))
        logitude = null;
    if(latitude.equals(""))
        latitude = null;
    System.out.println(id+","+logitude+","+latitude);
    if(id==null || id.equals(""))
    {
        out.println("沒Id");
        return ;
    }
    try
    {
        con = db.ConnectionPool.getCon();
        String sql = "update address set longitude = ? , latitude = ? , flg = '1'" +
            "where flg is null and id = ?" ;
        pst =con.prepareStatement(sql);
        pst.setString(1,logitude);
        pst.setString(2,latitude);
        pst.setInt(3,Integer.parseInt(id));
        pst.executeUpdate();
 
    }
    catch(java.sql.SQLException e)
    {
        e.printStackTrace();
    }
    finally
    {
        try
        {
 
            if(pst!=null)
            {
                pst.close();
                pst=null;
            }
            if(con!=null)
            {
                con.close();
                con=null;
            }
        }
        catch(java.sql.SQLException e)
        {
            System.out.println("Close Error!");
        }
    }%>

db.Connection.java

package db;
 
import com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource;
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
 
public class ConnectionPool {
 
    private Connection con = null;
 
    private static MysqlConnectionPoolDataSource ds = null;
 
    public ConnectionPool() {
        try {
            this.con = getPool().getConnection();
        } catch (SQLException localSQLException) {
            localSQLException.printStackTrace();
        }
    }
 
    public Connection getConnection() {
        return this.con;
    }
 
    public void CloseConnection() {
        try {
            if (this.con == null)
                return;
            this.con.close();
            this.con = null;
        } catch (SQLException localSQLException) {
        }
    }
 
    public static Connection getCon() throws SQLException {
        return getPool().getConnection();
    }
 
    public static void CloseCon(Connection con) {
        try {
            if (con == null)
                return;
            con.close();
            con = null;
        } catch (SQLException localSQLException) {
        }
    }
 
    public static DataSource getPool() throws SQLException {
        if (ds == null) {
 
            ds = new MysqlConnectionPoolDataSource();
 
            System.out.println("ServerName:" + "127.0.0.1");
            ds.setServerName("127.0.0.1");
            System.out.println("port:" + "3306");
            ds.setPortNumber(Integer.parseInt("3306"));
            System.out.println("DatabaseName:" + "test");
            ds.setDatabaseName("test");
            System.out.println("user:" + "root");
            ds.setUser("root");
            System.out.println("password:" + "12345");
            ds.setPassword("12345");
        }
 
        return ds;
    }
 
    public static void close(Object obj) {
        try {
            if (obj != null) {
                if (obj instanceof java.sql.Connection) {
                    ((java.sql.Connection) obj).close();
                    obj = null;
                } else if (obj instanceof java.sql.PreparedStatement) {
                    ((java.sql.PreparedStatement) obj).close();
                    obj = null;
                } else if (obj instanceof java.sql.ResultSet) {
                    ((java.sql.ResultSet) obj).close();
                    obj = null;
                } else if (obj instanceof java.sql.Statement) {
                    ((java.sql.Statement) obj).close();
                    obj = null;
                }
            }
        } catch (java.sql.SQLException e) {
            e.printStackTrace();
        }
    }
 
}

以上說明都在程式碼內,所以就不加詳述了。

利用JSP Server啟動執行後(可以直接把war檔放到tomcat\webapps\目錄下,會自動解開,war檔在最下面有提供)http://localhost:8080/GoogleMapLonLat/SearchLogLat.jsp

打開FireBug可以看到藍色的框一共做了四次,其中最後一次是終止,而紅色的框裡也回應了三次,二筆資料做了三次?這其實是有可能的,因為回應的時間不同是有可能發生的,不過並不會影響程式的執行。

GoogleMap1.png

原始碼如下:

以上


Related Posts Plugin for WordPress, Blogger...

5 回應 to “[jsp]利用Google Map查詢經緯度”

  1. 1
    gordon

    請問一下資料庫的連接是使用JDBC還是ODBC
    兩種我都試了可是都無法成功寫入
    是否可以提供ConnectionPool的程式碼
    謝謝!

    [回應]

    yku Replay:

    我不是有提供所有程式的原始碼嘛?
    你可以下載那個下去用,裡面就有connectionPool的用法了
    不然這一篇也有範例[Java]SiteMap Creater-簡單的SiteMap建立程式

    [回應]

    gordon Replay:

    yku 大大:
    可以用了MYSQL要密碼設12345就可以了
    不過下載那個裡面是WAR檔解開後只能看到ConnectionPool.class
    可否提供ConnectionPool.java,萬分感謝!
    初學者想參考一下是如何設定的
    程式碼直接貼上來也可以
    拜託了!!

    [回應]

    yku Replay:

    幸好程式碼還在!我把它補上了!你看看唄!!我一直以為有打包在裡面

    [回應]

  2. 2
    gordon

    yku:
    速度這麼快就放上來了
    再次謝謝你!

    [回應]

留下您想說的話:

*