如何將經緯度利用Google Map API顯示 C# VS2005 Sample Code

如何將經緯度利用Google Map API顯示 C# VS2005 Sample Code

日前寫了一篇如何用GPS抓取目前所在,並回傳至資料庫儲存,這篇將會利用這些回報的資料,將它顯示在地圖上,這個做法有兩種,最簡單的就是直接傳值到Google Maps上.

 

舉例來說,當我們知道經緯度後,只要將數據套到以下網址即可.

http://maps.google.com/maps?q=25.048346%2c121.516396

在參數q=後面,就可以加上經緯度了.

25.048346是Latitude緯度

%2c是空格

121.516396就是Longitude經度了.

範例畫面 :

image

 

而另一種做法就比這個複雜一點,要使用Google API來做,首先,要使用google API就必需要有google的帳號,沒帳號是無法申請的,當有google的帳號後,就可以到http://code.google.com/apis/maps/signup.html開始申請了.

image

最下方My web site URL就輸入各位的URL囉,如果輸入的與執行google map api的URL不同,那就無法執行了.所以這個URL務必輸入正確, 輸入正確的URL並將上方的CheckBox打勾後,就可以按Generate API Key了,如果已經登入GOOGLE的,就不會再跳登入畫面,之後就會跳到另一個畫面,上面就有Key及Example Code了,當有了這些,就可以開始自己寫Code了.

 

基本上,因為主要是Demo用的,所以設計介面很簡單.

map1

上面就一個DropDownList,因為先前的範例資料的關係,先手動在ITEM上加上1跟2.

而下方的地圖,就跟申請API時的Example Code一樣. 原始碼如下 :

 

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>GPS 位置地圖</title>
    <script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=輸入你的Key"
        type="text/javascript"></script>

    <script src="http://www.google.com/uds/api?file=uds.js&v=1.0&key=輸入你的Key"
        type="text/javascript"></script>

    <script src="http://www.google.com/uds/solutions/localsearch/gmlocalsearch.js" type="text/javascript"></script>

    <style type="text/css">  @import url("http://www.google.com/uds/css/gsearch.css");  
    @import url("http://www.google.com/uds/solutions/localsearch/gmlocalsearch.css");
    </style>

    <script type="text/javascript">
    //<![CDATA[
    function load(x,y,LocationName) {
      if (GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById("map"));
    var point = new GLatLng(x,y);
        map.setCenter(point, 16);
    map.addOverlay(new GMarker(point));
    map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());
    map.addControl(new GScaleControl());
    var lsc = new google.maps.LocalSearch();
    map.addControl(new google.maps.LocalSearch() , new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(10,20)));
    map.openInfoWindowHtml (map.getCenter(), LocationName);
      }
    }
    //]]>
    </script>
</head>
<body id="MainBody" runat="server">
    <form id="form1" runat="server">
    <div>
        <asp:DropDownList ID="ddl_Location" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddl_Location_SelectedIndexChanged"
            Width="500px">
            <asp:ListItem>1</asp:ListItem>
            <asp:ListItem Value="2">2</asp:ListItem>
        </asp:DropDownList><br />
        <br />
        <div id="map" style="width: 500px; height: 400px">
        </div>
    
    </div>
    </form>
</body>
</html>

 

 

只要將"輸入你的Key"的地方置換為你在Google MAP API申請到的Key即可.

 

   protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Request.QueryString.HasKeys())
            {
                string longitude = Request.QueryString.Get("lon");
                string latitude = Request.QueryString.Get("lat");
                string LN = Request.QueryString.Get(Server.UrlDecode("LN"));
                this.MainBody.Attributes.Add("onload", "load(" + longitude + "," + latitude + ",'" + LN + "')");
            }
            else
            {
                DataTable dt = GetLocation(ddl_Location.SelectedValue);
                if (dt.Rows.Count > 0)
                {
                    DataRow dr = dt.Rows[0];
                    this.MainBody.Attributes.Add("onload", "load(" + dr["Latitude"].ToString() + "," + dr["Longitude"].ToString() + ",'" + dr["updtime"].ToString() + "')");
                }
            }
        }
    }

    protected void ddl_Location_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            DataTable dt = GetLocation(ddl_Location.SelectedValue);
            if (dt.Rows.Count > 0)
            {
                DataRow dr = dt.Rows[0];
                this.MainBody.Attributes.Add("onload", "load(" + dr["Latitude"].ToString() + "," + dr["Longitude"].ToString() + ",'" + dr["updtime"].ToString() + "')");
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
        

    }

    private DataTable GetLocation(string UID)
    {
        try
        {
            string strconn = "Data Source=localhost;Initial Catalog=GPSDB;User Id=GPSUser;Password=gpsuser;";
            SqlConnection conn = new SqlConnection(strconn);
            string strcmd = "select Latitude,Longitude,UpdTime from GPSDB..gpstrace where UID=@UID";
            SqlCommand cmd = new SqlCommand(strcmd, conn);
            cmd.Parameters.AddWithValue("@UID", UID);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dt=new DataTable();
            da.Fill(dt);
            return dt;
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }

 

 

如此一來,就大功告成了,但或許有些人會有些遺問,那麼MAP上,可以自訂一些東西,例如不給搜尋列,這都是可以做到的,可以參考Google Map API Examples,這裡就有很多詳細的說明.

 

感覺起來,GPS定位的想法部份,好像到此就沒了,但在這過程中也發現到,其實Google Map有出Mobile版的,而它的定位可不只是局限在GPS衛星訊號,而是可以用手機的訊號去定位,也就是說,他是透過手機與基地台之間的傳輸來計算出所在位置,這樣就可以不受到手機沒有GPS功能模組或收不到衛星訊號所限制,這個概念其實也不算新,記得幾年前的Run!PC雜誌上就有篇文章是在介紹這個的,採用的技術是Java.

 

不過不管如何,可以預見的是,這個的應用會愈來愈多元,誰說未來還要自己去用電腦下載圖資再更新到自己的GPS裝置上,裝置上的地圖永遠會是最新的,加上Street View,也不用去看那電腦畫出來的3D的道路圖了,或許3G或無線上網的普及,這些運用將會更廣泛.

 

參考資料 :

Google Map API Examples

Google Map Mobile

 

原始碼 : GPSMap.zip