<%@ Page Language="VB" %>
<%@ Register TagPrefix="ttkGIS" Namespace="TatukGIS.IS" Assembly="TatukGIS.IS" %>
<%@ import Namespace="System.Data" %>
<%@ import Namespace="System.Data.OleDb" %>
<script runat="server">

    dim route as System.data.DataTable
    dim GisUtils as New API.XGIS_Utils
    dim ProjectionList as New API.XGIS_ProjectionList
    dim MapProjection  as API.XGIS_ProjectionAbstract
    dim MaxGPSPoints as integer

    Private RouteconnectionString as String
    Private dbConnection as OleDb.OleDbConnection
    Private odc as OleDb.OleDbCommand

    Sub Page_Load(sender As Object, e As EventArgs)

       'open database
        RouteconnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Ole DB Services=-4; Data Source=" + ConfigurationSettings.AppSettings("ttk_maps") + "StatePlan\routes.mdb"
        dbConnection = New OleDb.OleDbConnection(RouteconnectionString)         
        
       'set proper focus and projection
        if  Page.IsPostBack then
            session("focus") = chkbox_Focus.Checked
            session("snap") = chkbox_Snap.Checked
        else
            chkbox_Focus.Checked = session("focus")
            chkbox_Snap.Checked = session("snap")
        end if

       'set buttons and labels visibility and texts
        if Request.QueryString("stop") <> 2 then
            Btn_Start.Visible = False
            Btn_Stop.Visible = True
        else
            Btn_Stop.Visible = False
            Btn_Start.Visible = True
        end if

       'init route (GPS points table)
        init_Route()
    End Sub    

    Public Function SelectDBQuery(queryString As String) As DataTable
       'select query
        odc = New OleDb.OleDbCommand(queryString, dbConnection)

        Dim oda As OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter(odc)
        Dim ds As DataSet = New DataSet()
        oda.Fill(ds)

        Return (ds.Tables(0))
    End Function

    Sub init_Route()
       'init route
        Dim routeCar as string
        routeCar = "SELECT Pos, X, Y FROM route"
    
        Try
            route = SelectDBQuery(routeCar)
            Dim dvRoute As New DataView(route)
            MaxGPSPoints = dvRoute.Count - 1
        catch ex as Exception
            route = Nothing
        end try
    
       'set actual car position
        If session("StartCounting") = Nothing or Request.QueryString("stop") = 1 then
            Session("position") = 0
            session("StartCounting") = 1
        Else
            if Not Page.IsPostBack then Session("position") = Session("position") + 1
        End If
        If Session("position") > MaxGPSPoints then Session("position") = 0
    End Sub

    Function get_ActualPosition() as integer
        return(Session("position"))
    End Function
    
    Function reproject_Point(dt as System.data.DataTable, pos as integer) as API.XGIS_Point

        dim pu, pp as API.XGIS_Point
        dim cordu, cordp as API.XGIS_Coordinate

        pu = GisUtils.GisPoint( dt.Rows(pos).Item("X"), dt.Rows(pos).Item("Y") )
        cordu = New API.XGIS_Coordinate
        cordu.x = pu.x*Math.PI/180
        cordu.y = pu.y*Math.PI/180
        cordu.z = Nothing
        cordp = MapProjection.Projected(cordu)
        pp = New API.XGIS_Point
        pp.x = cordp.x
        pp.y = cordp.y
        Lbl_Pos.Text = "<b>X:</b>" &GisUtils.GisLongitudeToStr(cordu.x) & "<b>Y:</b>" &GisUtils.GisLatitudeToStr(cordu.y)

        return(pp)

    End Function    

    Sub GIS_Load(sender As Object, e As EventArgs)
        try
            GIS.Open( ConfigurationSettings.AppSettings("ttk_maps") + "StatePlan\Va_track.ttkgp" )
        Catch EX As Exception
            Response.Redirect("MapError.aspx")
        end Try

       'set up projection for VIRGINIA State Plan (Lambert Conformal Conic)
       '_central_meridian       -78 30
       '_latitude_of_origin     37 40
       '_false_easting          3500000
       '_false_northing         2000000
       '_standard_parallel_1    38 02
       '_standard_parallel_2    39 12

        MapProjection = ProjectionList.FindEx("LAM")
        MapProjection.SetUp(GisUtils.GisStrToLongitude("-78 30"), GisUtils.GisStrToLatitude("37 40"), 3500000, 2000000, GisUtils.GisStrToLatitude("38 02"), GisUtils.GisStrToLatitude("39 12"), 0, 0, 0, 0, 0, 0, 0, 0, 0)

    End Sub

    Sub GIS_BeforePaint(sender As Object, e As PaintEventArgs)
        dim SymbolList As New API.XGIS_SymbolList


        dim lt, ll  As API.XGIS_LayerVector
        dim car, pshp, shp_tmp, lshp As API.XGIS_Shape
        dim ex as API.XGIS_Extent
        dim pt as API.XGIS_Point
        dim p as API.XPoint
        dim i As Integer
        dim uid as integer

        if GIS.API.IsEmpty Then Exit Sub

       'add a new layer
        lt = New API.XGIS_LayerVector
        GIS.API.Add(lt)
        lt.Name = "carRoad"

       'add WGS84 GPS points which is get from outside
        pshp = lt.CreateShape(API.XGIS_ShapeType.XgisShapeTypeMultiPoint)
        pshp.Params.Marker.Color = Convert.ToUInt32(RGB(50,50,250))
        pshp.Params.Marker.Style = API.XGIS_MarkerStyle.XgisMarkerStyleCircle
        pshp.Params.Marker.Size = -12
        pshp.Lock(API.XGIS_Lock.XgisLockExtent)
        pshp.AddPart()
        for i=0 to get_ActualPosition()
            pshp.AddPoint( reproject_Point(route, i))
        next
        pshp.Unlock()

       'create line to get proper angle necessary to rotate car
        lshp = lt.CreateShape(API.XGIS_ShapeType.XgisShapeTypeArc)
        lshp.AddPart()
        lshp.Lock(API.XGIS_Lock.XgisLockExtent)
       'draw points that car should draw (snapped if necessary)        
        for i=0 to get_ActualPosition()
            shp_tmp = lt.CreateShape(API.XGIS_ShapeType.XgisShapeTypePoint)
            shp_tmp.Params.Marker.Color = Convert.ToUInt32(RGB(250,50,50))
            shp_tmp.Params.Marker.Style = API.XGIS_MarkerStyle.XgisMarkerStyleCircle
            shp_tmp.Params.Marker.Size = -8
            shp_tmp.Lock(API.XGIS_Lock.XgisLockExtent)
            shp_tmp.AddPart()
            pt = reproject_Point(route, i)            
            shp_tmp.AddPoint( pt )
            if session("snap") then
               'snap point
                shp_tmp.SetPosition( pt, GIS.API.Get("streets"), 50)
            end if
            shp_tmp.Unlock()
            if i > (get_ActualPosition() - 2) then
               'add onty to last point to line
                lshp.AddPoint( shp_tmp.Centroid() )
            end if
        next

        dim angle as double
        angle = lshp.GetAngle(True)

       'draw a car
        car = lt.CreateShape(API.XGIS_ShapeType.XgisShapeTypePoint)
        car.Params.Marker.Symbol = SymbolList.Prepare(ConfigurationSettings.AppSettings("ttk_maps") + "StatePlan\car.cgm")
        if i = 1 then
            car.Params.Marker.SymbolRotate = Math.Pi/2 + 3.5
        else
            car.Params.Marker.SymbolRotate = Math.Pi/2 + angle
        end if
        car.Params.Marker.Size = -20
        car.Params.Marker.Color = Convert.ToUInt32(RGB(250,50,50))
        car.Params.Marker.OutlineColor = Convert.ToUInt32(RGB(200,0,0))
        car.Params.Labels.OutlineWidth = -1
        car.Lock(API.XGIS_Lock.XgisLockExtent)
        car.AddPart()
        car.AddPoint( reproject_Point(route, get_ActualPosition()))
        if session("snap") then
            car.SetPosition( reproject_Point(route, get_ActualPosition()), GIS.API.Get("streets"), 50)
            p = GIS.API.MapToScreen(pt)
            uid = GIS.Locate( "streets", p.X, p.Y )
            Lbl_streetName.text = "<b>Street:</b> " & GIS.Field("streets", uid, "NAME2")
        else
        Lbl_streetName.text = ""
        end if
        car.Unlock()

       'reproject map
       'first - set layers projection and units (all layers has to be set to the same map )
        For i=0 to GIS.API.Items.Count -1
            ll = GIS.API.Items.Item(i)
            ll.Projection = MapProjection
            ll.Units.Units = API.XGIS_UnitsType.XgisUnitsTypeMeter
        Next

       'second - set map projection and adequate map units
        GIS.API.Projection = MapProjection
        GIS.API.Units.Units = API.XGIS_UnitsType.XgisUnitsTypeMeter

       'recalc map extent
        GIS.API.RecalcExtent()

       'else reverse previous map extent
        ex = Session("GISExtent")
        if not Session("GISExtent") is nothing then
            GIS.API.VisibleExtent = ex
        end if

       'if focus is set on car then center map on it
        if chkbox_Focus.Checked then
            p =  GIS.API.MapToScreen(car.Centroid())
            GIS.Center(p.x, p.y)
        end if

       'if focus is changed and scale is too small - change scale to bigger
        if chkbox_Focus.Checked then
            If GIS.Scale < 1/10000 then GIS.Scale = 1/10000
            session("focus_old") = chkbox_focus.Checked
        end if

    End Sub

    Sub GIS_Paint(sender As Object, e As PaintEventArgs)
       'draw map
        GIS.Draw

       'remember visible extent and scale to restore it after page redirection
        Session("GISExtent") = GIS.API.VisibleExtent
        Session("GISScale") = GIS.Scale

       'remember center point of visible map
        dim pt as API.XGIS_Point
        pt = GIS.API.Items.Item(0).Unproject(GISUtils.GisCenterPoint(GIS.API.VisibleExtent))
        Session("GISCenterPoint") = pt

        'write a scale
        Lbl_Scale.Text = "Scale: " &GIS.ScaleAsText
    End Sub

    Sub Btn_Stop_Click(sender As Object, e As EventArgs)
        Response.Redirect("TrackMap.aspx?stop=2")
    End Sub

    Sub Btn_Reset_Click(sender As Object, e As EventArgs)
        Response.Redirect("TrackMap.aspx?stop=1")
    End Sub

    Sub Btn_Start_Click(sender As Object, e As EventArgs)
        Response.Redirect("TrackMap.aspx?stop=0")
    End Sub

    Sub GIS_FullExtent_Click(sender As Object, e As ImageClickEventArgs)
        GIS.FullExtent
    End Sub

    Sub GIS_ZoomIn_Click(sender As Object, e As ImageClickEventArgs)
        Select Case GIS_Options.SelectedItem.Value
        Case 1
            GIS.Zoom = GIS.Zoom*2
        Case 2
            GIS.Zoom = GIS.Zoom*8
        Case Else
            GIS.ZoomIn
        End select
    End Sub

    Sub GIS_ZoomOut_Click(sender As Object, e As ImageClickEventArgs)
        Select Case GIS_Options.SelectedItem.Value
        Case 1
            GIS.Zoom = GIS.Zoom/2
        Case 2
            GIS.Zoom = GIS.Zoom/8
        Case Else
            GIS.ZoomOut
        End select
    End Sub

    Sub GIS_Click(sender As Object, e As ImageClickEventArgs)
        Select Case GIS_Options.SelectedItem.Value
        Case 1
            GIS.Center(e.X, e.Y)
            GIS_ZoomIn_Click(sender, e)
        Case 2
            GIS.Center(e.X, e.Y)
            GIS_ZoomIn_Click(sender, e)
        Case 3
            GIS.Center(e.X, e.Y)
        Case Else
            GIS.ZoomOut
        End select
    End Sub

</script>
<html>
<head>
    <link href="http://www.tatukgis.com/css/main.css" type="text/css" rel="stylesheet" /><%
    if Request.QueryString("stop") <> 2 then
    %> 
    <meta http-equiv="Refresh" content="3; URL=TrackMap.aspx" />
    <%
    end if
    %>
</head>
<body>
    <form runat="server">
        <table cellspacing="0" cellpadding="0" border="0">
            <tbody>
                <tr>
                    <td nowrap="nowrap" align="left">
                        <asp:ImageButton id="GIS_FullExtent" onclick="GIS_FullExtent_Click" runat="server" ImageUrl="/TatukGIS_IS8/img/fullextent.gif"></asp:ImageButton>
                        <asp:ImageButton id="GIS_ZoomIn" onclick="GIS_ZoomIn_Click" runat="server" ImageUrl="/TatukGIS_IS8/img/zoomin.gif"></asp:ImageButton>
                        <asp:ImageButton id="GIS_ZoomOut" onclick="GIS_ZoomOut_Click" runat="server" ImageUrl="/TatukGIS_IS8/img/zoomout.gif"></asp:ImageButton>
                    </td>
                    <td nowrap="nowrap" align="left">
                        <asp:RadioButtonList id="GIS_Options" runat="server" RepeatDirection="Horizontal">
                            <asp:ListItem Value="1" Selected="True">Zoom x2</asp:ListItem>
                            <asp:ListItem Value="2">Zoom x8</asp:ListItem>
                            <asp:ListItem Value="3">Center</asp:ListItem>
                        </asp:RadioButtonList>
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <TTKGIS:XGIS_VIEWERIS id="GIS" onclick="GIS_Click" runat="server" onPaint="GIS_Paint" onBeforePaint="GIS_BeforePaint" BorderWidth="1px" BorderColor="CornflowerBlue" OnLoad="GIS_Load" Height="380px" Width="520px"></TTKGIS:XGIS_VIEWERIS>
                    </td>
                </tr>
                <tr>
                    <td align="right" colspan="2">
                        <asp:Label id="Lbl_Scale" runat="server" text="Scale:" cssclass="8font"></asp:Label>
                    </td>
                </tr>
            </tbody>
        </table>
        <br />
        <table width="522" bgcolor="#e0e0e0">
            <tbody>
                <tr>
                    <td align="right" width="130">
                        <asp:Button id="Btn_Reset" onclick="Btn_Reset_Click" runat="server" Text="Reset Position"></asp:Button>
                    </td>
                    <td align="left" width="140">
                        <asp:Button id="Btn_Start" onclick="Btn_Start_Click" runat="server" Text="Resume Tracking"></asp:Button>
                        <asp:Button id="btn_Stop" onclick="Btn_Stop_Click" runat="server" Text="Pause Tracking"></asp:Button>
                    </td>
                    <td align="left" width="90">
                        <asp:CheckBox id="chkbox_Focus" runat="server" Text="Focus car" Font-Bold="True" AutoPostBack="True"></asp:CheckBox>
                    </td>
                    <td align="left" width="100">
                        <asp:CheckBox id="chkbox_Snap" runat="server" Text="Snap route" Font-Bold="True" AutoPostBack="True"></asp:CheckBox>
                    </td>
                </tr>
                <tr>
                    <td align="left" colspan="4">
                        <hr />
                    </td>
                </tr>
                <tr>
                    <td align="left" colspan="2">
                        <asp:Label id="Lbl_Pos" runat="server"></asp:Label>
                    </td>
                    <td align="left" colspan="2">
                        <asp:Label id="Lbl_StreetName" runat="server"></asp:Label>
                    </td>
                </tr>
            </tbody>
        </table>
    </form>
</body>
</html>