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

Posted in Java, database, google, javascript, opensource, prototype, 教學 on 2010/4/26 by yku 瀏覽:554人次 — 留下回應

如果手上有一堆地址清單想要知道它們的經緯度如何?要怎麼做呢?這裡介紹一個很簡單的方法,利用二個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!");
        }
    }%>

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

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

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

GoogleMap1.png

原始碼如下:

 

以上



Related Posts with Thumbnails

留下您想說的話: