1. 程式人生 > >基於ASP.NET,AJAX,Sqlserver和百度地圖API開發的西南科技大學校園地圖

基於ASP.NET,AJAX,Sqlserver和百度地圖API開發的西南科技大學校園地圖

目錄

Login.aspx:

Login.aspx.cs:

Register.aspx

Register.aspx.cs:

isUserNameExist.aspx.cs:

Map.aspx:

Map.aspx.cs:

Web.config:

執行結果部分截圖:

專案原始碼:https://download.csdn.net/download/qq_40323256/10889242


  專案內容:

    1.利用ASP.NET實現使用者的登入與註冊,並將使用者的使用者名稱及密碼用Sqlserver資料庫儲存起來。

     2.此校園地圖可以實現根據輸入地圖名查詢地圖,輸入框輸入關鍵字可以自動聯想相關地址,滑鼠滾輪或者右鍵地圖檢視實現地圖的縮放,普通影像與衛星影像的互換,對工具條或比例尺的新增或刪除,開啟全景圖等功能。

注意事項:

        在專案的開發之前,需要在百度地圖開放者平臺申請密匙,此密匙是百度地圖為使用者免費提供的,人人都可以申請。具體申請方法見:https://jingyan.baidu.com/article/e73e26c0b5b75124adb6a786.html

Login.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="西南科技大學校園地圖.Login" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>登入賬號</title>
    <style type="text/css">
        a {
            text-decoration :none;
        }
        .login{
            margin-left :500px;
        }
        .head{
               text-align :center ;
               font-size :x-large ;
               color :blue   ;
           }
    </style>
</head>
<body>
    <form id="form1" runat="server">
            <br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
                <div class ="head ">
            歡迎登入西南科技大學校園地圖<br /><br />
        </div>
            <table class ="login " >
                 <tr>
                     <td>
                        使用者名稱: <asp:TextBox ID="txt_UserName" runat="server" Text="請輸入使用者名稱" 
                onfocus="javascript:if(this.value=='請輸入使用者名稱'){this.value=''}" 
                  ></asp:TextBox>
              <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" 
                  ControlToValidate="txt_UserName" ErrorMessage ="*  使用者名稱不能為空" ForeColor ="Red">
           </asp:RequiredFieldValidator>

                    </td>
                </tr>
                
                <tr>
                     <td>
                        密碼:&nbsp;&nbsp;&nbsp <asp:TextBox ID="txt_Password" runat="server" Text="請輸入密碼" 
                onfocus="javascript:if(this.value=='請輸入密碼'){this.value=''}" 
                  ></asp:TextBox>
              <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" 
                  ControlToValidate="txt_Password" ErrorMessage ="*  密碼不能為空" ForeColor ="Red">
           </asp:RequiredFieldValidator>

                    </td>
                </tr>
                
                <tr>
                    <td>
                                            <asp:Button ID="btn_Login_Visitor" runat="server" Text="遊客登入" OnClick="btn_Login_Visitor_Click" Width="84px" />
        &nbsp;&nbsp; &nbsp;<asp:Button ID="btn_Login" runat="server" Text="登入" OnClick="btn_Login_Click" Width="82px" />
       
            <asp:LinkButton ID="LinkButton_register" runat="server" OnClick="LinkButton1_Click">沒有賬號?註冊</asp:LinkButton>
                    </td>
                </tr>
          </table>   
       
    </form>
</body>
</html>

Login.aspx.cs:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace 西南科技大學校園地圖
{
    public partial class Login : System.Web.UI.Page
    {
       
        private string myConnStr = ConfigurationManager.ConnectionStrings["SQL"].ConnectionString;
        protected void Page_Load(object sender, EventArgs e)
        {
            Session["a"] = "遊客";
            Session["username"] = txt_UserName.Text;
            Session["password"] = txt_Password.Text;
        }

        protected void LinkButton1_Click(object sender, EventArgs e)
        {
            Response.Redirect("Register.aspx");
        }

        protected void btn_Login_Click(object sender, EventArgs e)
        {
            string username = txt_UserName.Text;
            string password = txt_Password.Text;
            if (Page.IsValid == true)
            {
                
                Session["a"] = username;
                string sql = "select * from Users where 
[email protected]
and [email protected]"; SqlParameter[] parameters = { new SqlParameter("@UserName", username), new SqlParameter("@Password", password) }; using (SqlConnection conn = new SqlConnection(myConnStr )) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = sql; cmd.Parameters.AddRange(parameters); DataSet ds = new DataSet(); SqlDataAdapter adapter = new SqlDataAdapter(cmd); adapter.Fill(ds); DataTable table = ds.Tables[0]; if (table != null) { Response.Redirect("Map.aspx"); } else { Response.Write(@"<script>alert('登入失敗!');</script>"); } } } } } protected void btn_Login_Visitor_Click(object sender, EventArgs e) { Response.Redirect("Map.aspx"); } } }

Register.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Register.aspx.cs" Inherits="西南科技大學校園地圖.Register" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>註冊賬號</title>
       <style type ="text/css" >
           a{
               text-decoration :none ;
           }
           .Register{
              margin-left :500px;
           }
           .head{
               text-align :center ;
               font-size :x-large ;
               color :blue   ;
           }
       </style>
</head>
<body>
    <form id="form1" runat="server">
        <br /><br /><br /><br /><br /><br /><br /><br /><br />
        <div class ="head ">
            歡迎註冊西南科技大學校園地圖<br /><br />
        </div>
        <table class ="Register " >
                 <tr>
            
                     <td >
                         使用者名稱:&nbsp;&nbsp;&nbsp;&nbsp<asp:TextBox ID="txt_UserName" runat="server" Text="" 
                  onblur="Valide_UserName(this.value)"></asp:TextBox>
                     </td>
                     <td>
                      <div id="result_UserName"></div>
                    </td>
                </tr>
                <tr>
                          <td>
                         密碼:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<asp:TextBox ID="txt_Password" runat="server" Text="" 
               
                  ></asp:TextBox>
                    </td>
                </tr>
                      <tr>
                          
                           
                                     <td>
                         確認密碼:<asp:TextBox ID="txt_rePassword" runat="server" Text="" 
               
                 onblur=""></asp:TextBox>
                    </td>
                          <td>
                              <asp:Label ID="label_IsPasswordEqual" runat="server" Text="" ForeColor ="Red" ></asp:Label>
                          </td>
                </tr>
            <tr>
                <td>
                    <asp:Button ID="btn_Login" runat="server" Text="註冊" Width ="150px" OnClick="btn_Login_Click" />
                    &nbsp;&nbsp;&nbsp;
                    <asp:LinkButton ID="LinkButton1" runat="server" OnClick ="LinkButton1_Click">已有賬號?登入</asp:LinkButton>
                </td>
            </tr>
        </table>
    </form>
</body>
</html>
<script type ="text/javascript" >

            var xmlHttp;
            if (window.XMLHttpRequest) {
                xmlHttp = new XMLHttpRequest();
            } else {
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            function Valide_UserName(str) 
            {

                    var name = document.getElementById("txt_UserName");
                    xmlHttp.open("Get", "isUserNameExist.aspx?name=" + str,true );
                    xmlHttp.onreadystatechange= onmessageBack;
                    xmlHttp.send(null);

                    function onmessageBack()
                    {
                        if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
                        {
                        document.getElementById("result_UserName").innerHTML = xmlHttp.responseText;
                        }
                    }
            }


</script>

Register.aspx.cs:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace 西南科技大學校園地圖
{
    public partial class Register : System.Web.UI.Page
    {
        private string myConnStr = ConfigurationManager.ConnectionStrings["SQL"].ConnectionString;
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void LinkButton1_Click(object sender, EventArgs e)
        {
            Response.Redirect("Login.aspx");
        }

        protected void btn_Login_Click(object sender, EventArgs e)
        {
            string username = txt_UserName.Text.ToString();
            string password = txt_Password.Text.ToString();
            string repassword = txt_rePassword.Text.ToString();
            

            if(username == "")
            {
                Response.Write("<script>alert('使用者名稱不能為空');</script>");
                txt_UserName.Text  = "";
            }
            if(!(password ==repassword ))
            {
                Response.Write("<script>alert('兩次輸入密碼不一致,請重新輸入!');</script>");
                txt_Password.Text = "";
                txt_rePassword.Text = "";

            }
            if(!(username == "")&(password ==repassword))
            {
                
              string sql = "Insert into Users(UserName, Password) values(@UserName,@Password)";
                SqlParameter[] parameters = { new SqlParameter("@UserName", username), new SqlParameter("@Password", password) };
                using (SqlConnection conn = new SqlConnection(myConnStr ))
                {
                    conn.Open();
                    using (SqlCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = sql;
                        cmd.Parameters.AddRange(parameters);
                        cmd.ExecuteNonQuery();
                    }
                }

                Response.Write(@"<script>alert('註冊成功!');</script>");
            }
        }
    }
}

isUserNameExist.aspx.cs:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace 西南科技大學校園地圖
{
    public partial class isUserNameExist : System.Web.UI.Page
    {
        private string myConnStr = ConfigurationManager.ConnectionStrings["SQL"].ConnectionString;

        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Expires = -1;
            string name = this.Request.QueryString["name"];

            string mydr;
            SqlConnection myConn = new SqlConnection(myConnStr);
            string sql = "SELECT UserName from Users WHERE UserName=";
            sql = sql + "'" + name + "'";
            SqlCommand sqlCommand = new SqlCommand(sql, myConn);
            try
            {
                myConn.Open();
                if (name != "")
                {
                    if (sqlCommand.ExecuteScalar() != null)
                    {
                        mydr = sqlCommand.ExecuteScalar().ToString();
                        Response.Write("* 該使用者名稱-"+name +"-已存在,請重新輸入");
                        
                        Response.End();
                    }
                    else
                    {
                        Response.Write("√");
                        Response.End();
                    }
                }
                else
                {
                    Response.Write("請輸入使用者名稱!");
                    Response.End();
                }
            }
            catch (SqlException se)
            {

                Response.Write(se.Message + "<br>");
                Response.End();
            }
            finally
            {
                myConn.Close();
            }
        }
    }
}

Map.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Map.aspx.cs" Inherits="西南科技大學校園地圖.Map" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=eyAhsPkzLGmd2fAiQsWbs7heZndBavPt"></script>
    <title>西南科技大學校園地圖</title>
    <style type="text/css">
        #allmap {
            width: 1139px;
            height: 600px;
            overflow: hidden;
            font-family: "微軟雅黑";
            float: left;
            margin: 0;
        }

        .font {
            font-size: large;
            color: blue;
            font-style: italic;
        }

        .top_left{
            height: 50px;
            width: 75%;
            color: #0066FF;
            background-color: #FFFFCC;
            font-size: xx-large;
            font-weight: bolder;
            font-style: normal;
            text-align: center;
            float :left ;
        }
        .top_middle{
            height: 50px;
            width: 5.5%;
            color: #0066FF;
            background-color: #FFFFCC;
            font-size: large;
            font-style :italic ;
            
            text-align: center;
            float :left ;
        }
         .top_right{
            height: 50px;
            width:14%;
            color:aliceblue ;
            background-color:coral ;
            
            font-weight: bolder;
            font-style: normal;
            text-align: center;
            float :left ;
        }

        body {
            margin: 0;
            padding: 0;
        }

        .m_l {
            width: 25%;
            height: 600px;
            background-color: papayawhip;
            float: left;
        }

        .m_r {
            width: 75%;
            height: 600px;
            background-color: white;
            float: left;
        }

        .foot {
            height: 110px;
            width: 100%;
            background-color: deepskyblue;
            float: left;
            clear: left;
            color: black;
            font-size: larger;
            text-align: center;
        }
    </style>
</head>
<body>
     <form id="form1" runat="server">
          <div class="top_left ">
        西南科技大學校園地圖
    </div>
 <div class ="top_middle ">
  <asp:Label ID="Label_Hello" runat="server" Text="你好!" Font-Size="Large"  Width ="100%" Height ="100%" BackColor ="#FFFFCC" ForeColor="black"></asp:Label>
     
 </div>
          <div class ="top_middle " >
  <asp:Label ID="Label_UserName" runat="server" Text="遊客" Font-Size="Large"  Width ="100%" Height ="100%" BackColor ="#FFFFCC" ForeColor="black"></asp:Label>
     
 </div>
         <div class ="top_right ">
             <asp:Button ID="btn_Exit" runat="server" Text="退出登入" Width ="100%" Height ="100%" BackColor ="#ff3300" ForeColor="White" Font-Size="Large" OnClick ="btn_Exit_Click"/>
         </div>
            
    <div class="m_l font  ">
        &nbsp;&nbsp;  <input id="btn_AddControl" type="button" value="新增工具條/比例尺" onclick="add_control()" />
        &nbsp; &nbsp; <input id="btn_DelControl" type="button" value="刪除工具條/比例尺" onclick="delete_control()" /><br /><br />

        
	 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<div>請輸入:<input type="text" id="suggestId" size="20" value="西南科技大學" style="width:150px;" /></div>
	<div id="searchResultPanel" style="border:1px solid #C0C0C0;width:150px;height:auto; display:none;"></div>

    </div>




    <div id="allmap">
    </div>

    <div class="foot">
        WebGIS課程實驗設計
    </div>
 </form>
   
</body>
</html>
<script type="text/javascript">


    var map = new BMap.Map("allmap");
    map.centerAndZoom(new BMap.Point(104.701, 31.539), 17);
    //顯示地圖
    //新增地圖型別控制元件
    map.addControl(new BMap.MapTypeControl({
        mapTypes: [
            BMAP_NORMAL_MAP,
            BMAP_HYBRID_MAP
        ]
    }));
    map.setCurrentCity("西南科技大學");          // 設定地圖顯示的城市 此項是必須設定的
    map.enableScrollWheelZoom(true);     //開啟滑鼠滾輪縮放



    //新增控制元件
    var top_left_control = new BMap.ScaleControl({ anchor: BMAP_ANCHOR_TOP_LEFT });// 左上角,新增比例尺
    var top_left_navigation = new BMap.NavigationControl();  //左上角,新增預設縮放平移控制元件
    var top_right_navigation = new BMap.NavigationControl({ anchor: BMAP_ANCHOR_TOP_RIGHT, type: BMAP_NAVIGATION_CONTROL_SMALL }); //右上角,僅包含平移和縮放按鈕
    //新增控制元件和比例尺
    function add_control()
    {
        map.addControl(top_left_control);
        map.addControl(top_left_navigation);
        map.addControl(top_right_navigation);
    }
    //移除控制元件和比例尺
    function delete_control()
    {
        map.removeControl(top_left_control);
        map.removeControl(top_left_navigation);
        map.removeControl(top_right_navigation);
    }


    //全景地圖
    map.enableScrollWheelZoom(true);
    // 覆蓋區域圖層測試
    map.addTileLayer(new BMap.PanoramaCoverageLayer());

    var stCtrl = new BMap.PanoramaControl(); //構造全景控制元件
    stCtrl.setOffset(new BMap.Size(100, 10));
    map.addControl(stCtrl);//新增全景控制元件

    
    
    //滑鼠右鍵放大縮小
    var menu = new BMap.ContextMenu();
    var txtMenuItem = [
        {
            text: '放大',
            callback: function () { map.zoomIn() }
        },
        {
            text: '縮小',
            callback: function () { map.zoomOut() }
        }
    ];
    for (var i = 0; i < txtMenuItem.length; i++)
    {
        menu.addItem(new BMap.MenuItem(txtMenuItem[i].text, txtMenuItem[i].callback, 100));
    }
    map.addContextMenu(menu);


    //關鍵字提示輸入
    	function G(id) {
		return document.getElementById(id);
	}

    	var ac = new BMap.Autocomplete(    //建立一個自動完成的物件
		{"input" : "suggestId"
		,"location" : map
	});

	ac.addEventListener("onhighlight", function(e) {  //滑鼠放在下拉列表上的事件
	var str = "";
		var _value = e.fromitem.value;
		var value = "";
		if (e.fromitem.index > -1) {
			value = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
		}    
		str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;
		
		value = "";
		if (e.toitem.index > -1) {
			_value = e.toitem.value;
			value = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
		}    
		str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;
		G("searchResultPanel").innerHTML = str;
	});

	var myValue;
	ac.addEventListener("onconfirm", function(e) {    //滑鼠點選下拉列表後的事件
	var _value = e.item.value;
		myValue = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
		G("searchResultPanel").innerHTML ="onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue;
		
		setPlace();
	});

	function setPlace(){
		map.clearOverlays();    //清除地圖上所有覆蓋物
		function myFun(){
			var pp = local.getResults().getPoi(0).point;    //獲取第一個智慧搜尋的結果
			map.centerAndZoom(pp, 18);
			map.addOverlay(new BMap.Marker(pp));    //新增標註
		}
		var local = new BMap.LocalSearch(map, { //智慧搜尋
		  onSearchComplete: myFun
		});
		local.search(myValue);
	}

</script>

Map.aspx.cs:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace 西南科技大學校園地圖
{
    public partial class Map : System.Web.UI.Page
    {
      
        protected void Page_Load(object sender, EventArgs e)
        {

            if(Session["a"].ToString () == "遊客")
            {
                Label_UserName.Text = "遊客";
            }else
            {
                Label_UserName.Text = Session["a"].ToString();
            }
            
        }


        protected void btn_Delete_Click(object sender, EventArgs e)//登出賬號
        {

        }

        protected void btn_Exit_Click(object sender, EventArgs e)//退出登入
        {
            Response.Redirect("~/Login.aspx");

        }
    }
}

Web.config:

<?xml version="1.0" encoding="utf-8"?>

<!--
  有關如何配置 ASP.NET 應用程式的詳細資訊,請訪問
  https://go.microsoft.com/fwlink/?LinkId=169433
-->

<configuration>
    <system.web>
      <compilation debug="true" targetFramework="4.0" />
    </system.web>

  <connectionStrings>

    <add name="SQL" connectionString="data source=DESKTOP-NA2OPPJ\SQLEXPRESS;database=users;user id=sa;pwd=123"/>


  </connectionStrings>

</configuration>

執行結果部分截圖:

專案原始碼:https://download.csdn.net/download/qq_40323256/10889242