Source Code RoutingEdition ProjectTemplates CityRoutingAndDirections Web CS.zip
ready-functions.cs
$(document).ready(function () {
window.onload = resizeElementHeight();
$(window).resize(resizeElementHeight);
$("#toggle").bind("click", function () {
if ($("#leftContainer").is(':visible')) {
$("#collapse").attr("src", "Images/expand.gif");
$("#map-content").css("width", "100%");
$("#toggle").css("left", "0px");
$("#leftContainer").hide();
}
else {
$("#leftContainer").show();
$("#collapse").attr("src", "Images/collapse.gif");
$("#map-content").css("width", "80%");
$("#toggle").css("left", "20%");
}
resizeElementHeight();
});
$("#warningDialog").dialog({
autoOpen: false,
modal: true,
buttons: {
Ok: function () {
$(this).dialog("close");
}
}
});
$("#outofBoundaryWarning").dialog({
autoOpen: false,
modal: true,
buttons: {
Ok: function () {
$(this).dialog("close");
}
}
});
var btnTracks = $("#divTrackMode").find("input");
for (var i = 0; i < btnTracks.length; i++) {
$(btnTracks[i]).bind("click", function () {
var btnTracks = $("#divTrackMode").find("input");
for (var i = 0; i < btnTracks.length; i++) {
$(btnTracks[i]).css("border", "0px solid #D3D3D3");
$(btnTracks[i]).css("background-color", "transparent");
}
$(this).css("border", "1px solid #D3D3D3");
$(this).css("background-color", "#eeeeee");
});
};
$("#divTrackMode input[type=image]").bind("click", function () {
var mode = $(this).attr("command");
switch (mode) {
case "ClearAll":
$("#btnPanMap").trigger("click");
break;
case "Undo":
$("#btnPanMap").trigger("click");
break;
case "Polygon":
$(this).trigger("click");
break;
case "PanMap":
$("#btnPanMap").trigger("click");
break;
default: break;
}
});
});
var OnMapCreated = function (map) {
map.events.register("mousemove", map, function (e) {
var mouseCoordinate = this.getLonLatFromPixel(new OpenLayers.Pixel(e.clientX, e.clientY));
if (mouseCoordinate) {
$("#spanMouseCoordinate").text("X:" + mouseCoordinate.lon.toFixed(6) + " Y: " + mouseCoordinate.lat.toFixed(6));
}
});
};
// Add the loading image.
var pageManager = Sys.WebForms.PageRequestManager.getInstance();
pageManager.add_beginRequest(function () {
$("#loading").show();
});
pageManager.add_endRequest(function () {
$("#loading").hide();
});
function resizeElementHeight() {
var documentheight = $(window).height();
var contentDivH = documentheight - $("#footer").height() - $("#header").height() - 1;
$("#content-container").height(contentDivH + "px");
$("#leftContainer").height(contentDivH + "px");
$("#map-content").height(contentDivH + "px");
$("#toggle").css("line-height", contentDivH + "px");
if (contentDivH > 500) {
$("#queryResultUpdatePanel").height(contentDivH - 365 + "px");
} else {
$("#queryResultUpdatePanel").visible = false;
}
$("#mapContainer").height(contentDivH + "px");
// refresh the map.
webMap.GetOpenLayersMap().updateSize();
}
function pageLoad() {
resizeElementHeight();
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ThinkGeo.MapSuite.RoutingExamples
{
public enum ContextMenuItemType
{
NoSure = 0,
StartPoint = 1,
EndPoint = 2,
StopPoint = 3
}
}
RouteDirection.cs
using System;
using ThinkGeo.MapSuite.Core;
using ThinkGeo.MapSuite.Routing;
namespace ThinkGeo.MapSuite.RoutingExamples
{
public class RouteDirection
{
private static string directionImageUriTemplate = "../Images/Directions/{0}";
private string directionImageUriString;
private GeographyUnit geographyUnit;
private DistanceUnit lengthUnit;
private Feature roadFeature;
private string roadNameColumnName;
private RouteSegment roadSegment;
private Feature roadSegmentFeature;
public RouteDirection(RouteSegment roadSegment, Feature roadFeature, string roadNameColumnName, GeographyUnit geographyUnit, DistanceUnit lengthUnit)
{
this.roadSegment = roadSegment;
this.roadFeature = roadFeature;
this.roadNameColumnName = roadNameColumnName;
this.geographyUnit = geographyUnit;
this.lengthUnit = lengthUnit;
}
public DrivingDirection Direction
{
get
{
if (roadSegment != null)
{
return roadSegment.DrivingDirection;
}
else
{
return DrivingDirection.Back;
}
}
}
public Uri DirectionImageUri
{
get
{
switch (Direction)
{
case DrivingDirection.Back:
directionImageUriString = "back.png";
break;
case DrivingDirection.Forward:
directionImageUriString = "Forward.png";
break;
case DrivingDirection.Invalid:
directionImageUriString = "Invalid.png";
break;
case DrivingDirection.LeftForward:
directionImageUriString = "LeftForward.png";
break;
case DrivingDirection.Right:
directionImageUriString = "Right.png";
break;
case DrivingDirection.RightBack:
directionImageUriString = "RightBack.png";
break;
case DrivingDirection.RightForward:
directionImageUriString = "RightForward.png";
break;
case DrivingDirection.LeftBack:
directionImageUriString = "LeftBack.png";
break;
case DrivingDirection.Left:
directionImageUriString = "Left.png";
break;
}
return new Uri(string.Format(directionImageUriTemplate, directionImageUriString), UriKind.RelativeOrAbsolute);
}
}
public GeographyUnit GeographyUnit
{
get { return geographyUnit; }
set { geographyUnit = value; }
}
public string Length
{
get
{
string length = string.Empty;
double value = Math.Round(((LineBaseShape)RoadFeature.GetShape()).GetLength(GeographyUnit, lengthUnit), 2);
if (lengthUnit == DistanceUnit.Mile)
{
length = string.Format("{0} mi", value);
}
else
{
length = string.Format("{0} km", value);
}
return length;
}
}
public DistanceUnit LengthUnit
{
get { return lengthUnit; }
set { lengthUnit = value; }
}
public Feature RoadFeature
{
get { return roadFeature; }
set { roadFeature = value; }
}
public string RoadName
{
get
{
if (!string.IsNullOrEmpty(RoadNameColumnName))
{
return roadFeature.ColumnValues[RoadNameColumnName];
}
else
{
return string.Empty;
}
}
}
public string RoadNameColumnName
{
get { return roadNameColumnName; }
set { roadNameColumnName = value; }
}
}
}
RoutePathAndDirection.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using ThinkGeo.MapSuite.Core;
using ThinkGeo.MapSuite.Routing;
namespace ThinkGeo.MapSuite.RoutingExamples
{
public class RoutePathAndDirection
{
private readonly List<PointShape> stopPoints;
private readonly List<string> avoidableFeatureIds;
private PointShape endPoint;
private PointShape startPoint;
private RoutingEngine routingEngine;
private FeatureSource barrierFeatureSource;
public RoutePathAndDirection()
{ }
public RoutePathAndDirection(RoutingEngine routingEngine, PointShape startPoint, PointShape endPoint)
: this(routingEngine, startPoint, endPoint, null)
{
}
public RoutePathAndDirection(RoutingEngine routingEngine, PointShape startPoint, PointShape endPoint, FeatureSource barrierFeatureSource)
: this(routingEngine, startPoint, endPoint, barrierFeatureSource, new string[] { })
{
}
public RoutePathAndDirection(RoutingEngine routingEngine, PointShape startPoint, PointShape endPoint, FeatureSource barrierFeatureSource, IEnumerable<string> avoidableFeatureIds)
: this(routingEngine, startPoint, endPoint, barrierFeatureSource, avoidableFeatureIds, new PointShape[] { })
{
}
public RoutePathAndDirection(RoutingEngine routingEngine, PointShape startPoint, PointShape endPoint, FeatureSource barrierFeatureSource, IEnumerable<PointShape> stopPoints)
: this(routingEngine, startPoint, endPoint, barrierFeatureSource, new string[] { }, stopPoints)
{
}
public RoutePathAndDirection(RoutingEngine routingEngine, PointShape startPoint, PointShape endPoint, FeatureSource barrierFeatureSource, IEnumerable<string> avoidableFeatureIds, IEnumerable<PointShape> stopPoints)
{
this.endPoint = endPoint;
this.startPoint = startPoint;
this.routingEngine = routingEngine;
this.barrierFeatureSource = barrierFeatureSource;
this.stopPoints = new List<PointShape>(stopPoints);
this.avoidableFeatureIds = new List<string>(avoidableFeatureIds);
routingEngine.RoutingAlgorithm.FindingRoute += RoutingAlgorithm_FindingRoute;
}
public PointShape StartPoint
{
get { return startPoint; }
set { startPoint = value; }
}
public PointShape EndPoint
{
get { return endPoint; }
set { endPoint = value; }
}
public List<PointShape> StopPoints
{
get { return stopPoints; }
}
public RoutingEngine RoutingEngine
{
get { return routingEngine; }
set { routingEngine = value; }
}
public FeatureSource BarrierFeatureSource
{
get { return barrierFeatureSource; }
set { barrierFeatureSource = value; }
}
public List<string> AvoidableFeatureIds
{
get { return avoidableFeatureIds; }
}
public RoutingResult GetRoute()
{
if (stopPoints != null && !stopPoints.Any())
{
RoutingResult result = routingEngine.GetRoute(startPoint, endPoint);
return result;
}
else
{
Collection<PointShape> points = new Collection<PointShape>();
points.Add(startPoint);
foreach (PointShape stopPoint in stopPoints)
{
points.Add(stopPoint);
}
points.Add(endPoint);
// Filter the invalid point.
Collection<PointShape> availablePoint = FilterInvalidPoints(points);
RoutingResult result = null;
for (int i = 0; i < availablePoint.Count - 1; i++)
{
RoutingResult tempResult = routingEngine.GetRoute(availablePoint[i], availablePoint[i|+ 1]);
result = CombineRoutingResult(result, tempResult);
}
return result;
}
}
private Collection<PointShape> FilterInvalidPoints(IEnumerable<PointShape> points)
{
Collection<PointShape> result = new Collection<PointShape>();
barrierFeatureSource.Open();
Collection<Feature> barrierFeatures = barrierFeatureSource.GetAllFeatures(ReturningColumnsType.NoColumns);
foreach (PointShape point in points)
{
bool inBarrier = barrierFeatures.Any(a => a.Contains(new Feature(point)));
if (!inBarrier) result.Add(point);
}
return result;
}
private RoutingResult CombineRoutingResult(RoutingResult baseResult, RoutingResult additionalResult)
{
if (baseResult == null)
{
baseResult = new RoutingResult();
baseResult.Distance = additionalResult.Distance;
baseResult.Weight = additionalResult.Weight;
baseResult.Route = additionalResult.Route;
additionalResult.Features.ForEach(a => baseResult.Features.Add(a));
additionalResult.OrderedStops.ForEach(a => baseResult.OrderedStops.Add(a));
additionalResult.RouteSegments.ForEach(a => baseResult.RouteSegments.Add(a));
}
else
{
baseResult.Distance += additionalResult.Distance;
baseResult.Weight += additionalResult.Weight;
Collection<Vertex> vertexes = new Collection<Vertex>();
baseResult.Route.Vertices.ForEach(vertexes.Add);
additionalResult.Route.Vertices.ForEach(vertexes.Add);
baseResult.Route = new LineShape(vertexes);
additionalResult.Features.ForEach(a => baseResult.Features.Add(a));
additionalResult.OrderedStops.ForEach(a => baseResult.OrderedStops.Add(a));
additionalResult.RouteSegments.ForEach(a => baseResult.RouteSegments.Add(a));
}
return baseResult;
}
private void RoutingAlgorithm_FindingRoute(object sender, FindingRouteRoutingAlgorithmEventArgs e)
{
Collection<string> beContainedFeatureIds = new Collection<string>();
barrierFeatureSource.Open();
Collection<string> startPointAdjacentIds = e.RouteSegment.StartPointAdjacentIds;
Collection<string> endPointAdjacentIds = e.RouteSegment.EndPointAdjacentIds;
foreach (string id in startPointAdjacentIds.Where(id => avoidableFeatureIds.Contains(id)))
{
beContainedFeatureIds.Add(id);
}
foreach (string id in endPointAdjacentIds.Where(id => avoidableFeatureIds.Contains(id)))
{
beContainedFeatureIds.Add(id);
}
// Remove the ones that be contained in the avoidable area
foreach (string id in beContainedFeatureIds)
{
if (e.RouteSegment.StartPointAdjacentIds.Contains(id))
{
e.RouteSegment.StartPointAdjacentIds.Remove(id);
}
if (e.RouteSegment.EndPointAdjacentIds.Contains(id))
{
e.RouteSegment.EndPointAdjacentIds.Remove(id);
}
}
}
}
}
StopItem.cs
using ThinkGeo.MapSuite.Core;
using System;
namespace ThinkGeo.MapSuite.RoutingExamples
{
public class StopItem
{
private PointShape locationPointShape;
private string locationPointShapeText;
private int number;
public StopItem(PointShape locationPointShape)
{
string pointText = string.Format("{0} , {1}", Math.Round(locationPointShape.X, 8), Math.Round(locationPointShape.Y, 8));
LocationPointShapeText = pointText;
this.locationPointShape = locationPointShape;
}
public int Number
{
get { return number + 1; }
set { number = value; }
}
public PointShape LocationPointShape
{
get
{
return locationPointShape;
}
}
public string LocationPointShapeText
{
get { return locationPointShapeText; }
set { locationPointShapeText = value; }
}
public StopItem Self
{
get { return this; }
}
}
}
Default.cs
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ThinkGeo.MapSuite.RoutingExamples.Default" %>
<%@ Register Assembly="WebEdition" Namespace="ThinkGeo.MapSuite.WebEdition" TagPrefix="cc1" %>
<!DOCTYPE html>
<html xml:en-us">
<head runat="server">
<title>City Routing and Directions</title>
<meta charset="UTF-8">
<link href="Images/MapSuite.ico" rel="shortcut icon" type="Images/x-icon" />
<link href="Styles/jquery-ui-1.10.4.custom.css" rel="stylesheet" type="text/css" />
<link href="Styles/Site.css" rel="stylesheet" type="text/css" />
<script src="Scripts/jquery-1.10.2.js" type="text/javascript"></script>
<script src="Scripts/jquery-ui-1.10.4.custom.js" type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div id="container">
<div id="header">
<div id="left-header">
<span id="header-mapsuite">Map Suite</span> <span id="header-title">City Routing and
Directions</span>
</div>
</div>
<div id="content-container">
<div id="leftContainer">
<div id="leftContent">
<h4>
Right click on the map to set up a route:
</h4>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div id="routeContainer">
<table id="resultTable">
<tbody>
<tr>
<td id="startIcon">
</td>
<td>
<asp:TextBox runat="server" AutoPostBack="True" ID="startPoint" ReadOnly="true"></asp:TextBox>
</td>
<td class="OperationIcon">
<asp:ImageButton ID="imgInvert" runat="server" ImageUrl="/Images/switch.png" OnClick="imgInvert_MouseLeftButtonDown"
ToolTip="Switch start and end search point" />
</td>
</tr>
<asp:Repeater ID="stopItemList" runat="server">
<ItemTemplate>
<tr>
<td class="stopIcon">
<asp:Label ID="Label1" class="number" runat="server" Text='<%# Eval("Number") %>'> </asp:Label>
</td>
<td>
<asp:TextBox ID="TextBox1" ToolTip='<%# Eval("Number") %>' runat="server" AutoPostBack="True"
Text='<%# Eval("LocationPointShapeText") %>' ReadOnly="true"></asp:TextBox>
</td>
<td class="OperationIcon">
<asp:ImageButton ID="removeStop" runat="server" OnCommand="RemoveStopPoint" CommandArgument='<%# Eval("Number") %>'
ImageUrl="/Images/remove.png" />
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
<tr>
<td id="endIcon">
</td>
<td>
<asp:TextBox runat="server" AutoPostBack="True" ID="endPoint" ReadOnly="true"></asp:TextBox>
</td>
</tr>
</tbody>
</table>
</div>
</ContentTemplate>
</asp:UpdatePanel>
<h4>
Tools:</h4>
<div id="divTrackMode" class="divBorder">
<asp:ImageButton ID="btnPanMap" runat="server" ToolTip="Pan the map" CommandArgument="PanMap"
CssClass="active" command="PanMap" OnCommand="SwitchTrackShapeMode_Command" ImageUrl="Images/Pan.png" />
<asp:ImageButton ID="btnDrawPolygon" runat="server" ToolTip="Draw areas to avoid traveling through"
CommandArgument="DrawPolygon" command="Polygon" OnCommand="SwitchTrackShapeMode_Command"
ImageUrl="Images/draw_polygon.png" />
<asp:ImageButton ID="btnUndo" runat="server" ToolTip="Undo last area drawn" CommandArgument="Undo"
command="Undo" OnCommand="SwitchTrackShapeMode_Command" ImageUrl="Images/undo.png" />
<asp:ImageButton ID="btnClearBarriers" runat="server" ToolTip="Delete all areas"
command="ClearAll" CommandArgument="ClearAllBarriers" OnCommand="SwitchTrackShapeMode_Command"
ImageUrl="Images/clear.png" />
</div>
<div class="text-right">
<asp:Button ID="btnGetDirections" runat="server" Text="Get Directions" OnClick="btnGetDirections_Click">
</asp:Button>
<asp:Button ID="btnClearAll" runat="server" Text="Reset Route" OnClick="btnClearAll_Click">
</asp:Button>
</div>
<div class="blueBanner">
Result
</div>
<asp:UpdatePanel ID="routingSetting" runat="server">
<ContentTemplate>
<div id="resultOption">
<asp:RadioButtonList AutoPostBack="True" OnSelectedIndexChanged="rblRouteMode_OnSelectedIndexChanged"
runat="server" ID="rblRouteMode" RepeatDirection="Horizontal" CellPadding="0"
CellSpacing="1" BorderColor="White">
<asp:ListItem Selected="True">Shortest</asp:ListItem>
<asp:ListItem>Fastest</asp:ListItem>
</asp:RadioButtonList>
<asp:DropDownList AutoPostBack="True" runat="server" ID="ddlDistanceUnit" OnSelectedIndexChanged="ddlDistanceUnit_SelectedIndexChanged">
<asp:ListItem Text="Miles"></asp:ListItem>
<asp:ListItem Text="Kilometers"></asp:ListItem>
</asp:DropDownList>
</ContentTemplate>
</asp:UpdatePanel>
</div>
<asp:UpdatePanel ID="queryResultUpdatePanel" runat="server">
<ContentTemplate>
<asp:Repeater ID="repeaterQueryResult" runat="server">
<HeaderTemplate>
<table id="resultTable">
<thead>
<tr>
<td class="header">
</td>
<td class="header">
Road Name
</td>
<td class="header">
Length
</td>
</tr>
</thead>
<tbody>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<asp:ImageButton ID="find" runat="server" ImageUrl='<%# Eval("DirectionImageUri") %>'
Height="15px" />
</td>
<td>
<%# Eval("RoadNameColumnName") %>
</td>
<td>
<%# Eval("Length") %>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</tbody> </table>
</FooterTemplate>
</asp:Repeater>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnGetDirections" />
<asp:AsyncPostBackTrigger ControlID="btnClearAll" />
</Triggers>
</asp:UpdatePanel>
</div>
</div>
<div id="toggle">
<img id="collapse" alt="collapse" src="Images/collapse.gif" />
</div>
<div id="map-content">
<asp:UpdatePanel ID="mapContentPanel" runat="server" style="height: 100%;">
<ContentTemplate>
<cc1:Map ID="webMap" runat="server" Height="100%" Width="100%" OnTrackShapeFinished="webMap_TrackShapeFinished">
</cc1:Map>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnClearAll" />
<asp:AsyncPostBackTrigger ControlID="stopItemList" />
<asp:AsyncPostBackTrigger ControlID="endPoint" />
<asp:AsyncPostBackTrigger ControlID="startPoint" />
<asp:AsyncPostBackTrigger ControlID="ddlDistanceUnit" />
<asp:AsyncPostBackTrigger ControlID="btnPanMap" />
<asp:AsyncPostBackTrigger ControlID="btnDrawPolygon" />
<asp:AsyncPostBackTrigger ControlID="btnUndo" />
<asp:AsyncPostBackTrigger ControlID="btnClearBarriers" />
</Triggers>
</asp:UpdatePanel>
</div>
</div>
<div id="footer">
<span id="spanMouseCoordinate"></span>
</div>
<div id="warningDialog" title="Warning Message">
<p>
The coordinate format is incorrect, please check the input coordinate.
</p>
</div>
<div id="outofBoundaryWarning" title="Warning Message">
<p>
Please note that this sample map is only able to analyze service areas within the
Austin city limits, which are indicated by a dashed red line. Click inside that
boundary for best results.
</p>
</div>
<div id="loading">
<img id="loading-image" src="/Images/loading.gif" alt="Loading..." />
</div>
<script type="text/javascript" src="Scripts/ready-functions.js"></script>
</form>
</body>
</html>
Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using ThinkGeo.MapSuite.Core;
using ThinkGeo.MapSuite.Routing;
using ThinkGeo.MapSuite.WebEdition;
namespace ThinkGeo.MapSuite.RoutingExamples
{
public partial class Default : Page
{
private static readonly string roadColumnName = "FULL_STREE";
private static readonly string rtgFastestFile = @"~\App_Data\austin_streets_fastest.rtg";
private static readonly string rtgShortestFile = @"~\App_Data\austin_streets_shortest.rtg";
private static readonly string austinCountyShapeFile = @"~\App_Data\AustinBorder.shp";
private static readonly string austinStreetShapeFile = @"~\App_Data\austin_streets.shp";
private static ShapeFileFeatureLayer routingShapeFile;
private static Dictionary<string, string> contextMenuItems;
private static Collection<StopItem> stopItems;
private static Collection<string> avoidableFeatureIds;
private static Feature newBarrierFeature;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
stopItems = new Collection<StopItem>();
avoidableFeatureIds = new Collection<string>();
routingShapeFile = new ShapeFileFeatureLayer(MapPath(austinStreetShapeFile));
// Initialize map
webMap.MapUnit = GeographyUnit.DecimalDegree;
webMap.CurrentExtent = new RectangleShape(-97.783553154785, 30.362039937378, -97.680175654785, 30.229261310914);
webMap.EditOverlay.TrackMode = TrackMode.None;
// Initialize map overlay and datasource.
InitializeMapOverlays();
InitializeMapContextMenu();
stopItemList.DataSource = new Collection<StopItem>();
stopItemList.DataBind();
repeaterQueryResult.DataSource = new Collection<RouteDirection>();
repeaterQueryResult.DataBind();
}
}
protected void btnGetDirections_Click(object sender, EventArgs e)
{
DisplayDirectionsPath();
}
protected void btnClearAll_Click(object sender, EventArgs e)
{
var routingOverlay = webMap.CustomOverlays["RoutingOverlay"] as LayerOverlay;
if (routingOverlay != null)
{
var routingLayer = routingOverlay.Layers.FirstOrDefault() as RoutingLayer;
if (routingLayer != null)
{
ClearBarriers();
stopItemList.DataSource = new Collection<StopItem>();
stopItemList.DataBind();
repeaterQueryResult.DataSource = new Collection<RouteDirection>();
repeaterQueryResult.DataBind();
imgInvert.CssClass = string.Empty;
routingLayer.StartPoint = null;
startPoint.Text = string.Empty;
routingLayer.EndPoint = null;
endPoint.Text = string.Empty;
stopItems.Clear();
routingLayer.StopPoints.Clear();
routingLayer.Routes.Clear();
routingOverlay.Redraw();
}
}
}
protected void imgInvert_MouseLeftButtonDown(object sender, EventArgs e)
{
var routingOverlay = webMap.CustomOverlays["RoutingOverlay"] as LayerOverlay;
if (routingOverlay != null)
{
var routingLayer = routingOverlay.Layers.FirstOrDefault() as RoutingLayer;
if (routingLayer != null)
{
PointShape start = routingLayer.StartPoint;
routingLayer.StartPoint = routingLayer.EndPoint;
routingLayer.EndPoint = start;
}
}
string endString = startPoint.Text;
startPoint.Text = endPoint.Text;
endPoint.Text = endString;
btnGetDirections_Click(null, null);
if (routingOverlay != null) routingOverlay.Redraw();
}
protected void webMap_TrackShapeFinished(object sender, EventArgs e)
{
LayerOverlay routingOverlay = webMap.CustomOverlays["RoutingOverlay"] as LayerOverlay;
InMemoryFeatureLayer barrierLayer = routingOverlay.Layers["BarrierLayer"] as InMemoryFeatureLayer;
Feature trackFeature = webMap.EditOverlay.Features[0];
if (trackFeature != null)
{
trackFeature.ColumnValues["Barrier"] = "Obstacle";
barrierLayer.InternalFeatures.Add(trackFeature);
newBarrierFeature = trackFeature;
webMap.EditOverlay.Features.Clear();
}
avoidableFeatureIds.Clear();
foreach (Feature feature in barrierLayer.InternalFeatures)
{
BaseShape barrierShape = feature.GetShape();
routingShapeFile.Open();
Collection<Feature> features = routingShapeFile.FeatureSource.GetFeaturesWithinDistanceOf(barrierShape, webMap.MapUnit, DistanceUnit.Meter, 1, ReturningColumnsType.NoColumns);
routingShapeFile.Close();
foreach (Feature avoidableFeature in features)
{
avoidableFeatureIds.Add(avoidableFeature.Id);
}
}
routingOverlay.Redraw();
}
protected void RemoveStopPoint(object sender, CommandEventArgs e)
{
LayerOverlay routingOverlay = webMap.CustomOverlays["RoutingOverlay"] as LayerOverlay;
var routingLayer = routingOverlay.Layers.FirstOrDefault() as RoutingLayer;
for (int i = 0; i < stopItems.Count; i++)
{
if (stopItems[i].Number.ToString() == e.CommandArgument.ToString())
{
routingLayer.StopPoints.Remove(stopItems[i].LocationPointShape);
stopItems.RemoveAt(i);
}
}
if (stopItems.Count < 1)
{
imgInvert.CssClass = string.Empty;
}
else
{
for (int i = 0; i < stopItems.Count; i++)
{
stopItems[i].Number = i;
}
}
routingLayer.Routes.Clear();
stopItemList.DataSource = stopItems;
stopItemList.DataBind();
routingOverlay.Redraw();
}
protected void rblRouteMode_OnSelectedIndexChanged(object sender, EventArgs e)
{
DisplayDirectionsPath();
}
protected void ddlDistanceUnit_SelectedIndexChanged(object sender, EventArgs e)
{
DisplayDirectionsPath();
ScaleBarAdornmentLayer adornmentLayer = webMap.AdornmentOverlay.Layers["ScaleBar"] as ScaleBarAdornmentLayer;
adornmentLayer.UnitFamily = ddlDistanceUnit.SelectedIndex == 0 ? UnitSystem.Imperial : UnitSystem.Metric;
}
protected void SwitchTrackShapeMode_Command(object sender, CommandEventArgs e)
{
switch (e.CommandArgument.ToString())
{
case "DrawPolygon":
webMap.EditOverlay.TrackMode = TrackMode.Polygon;
break;
case "Undo":
webMap.EditOverlay.TrackMode = TrackMode.None;
UndoTrack();
break;
case "ClearAllBarriers":
webMap.EditOverlay.TrackMode = TrackMode.None;
ClearBarriers();
break;
case "PanMap":
default:
webMap.EditOverlay.TrackMode = TrackMode.None;
break;
}
}
private void MenuItemClick(object sender, ContextMenuItemClickEventArgs e)
{
if (!IdentifyAddressPointRestriction(e.Location))
{
LayerOverlay routingOverlay = webMap.CustomOverlays["RoutingOverlay"] as LayerOverlay;
var routingLayer = routingOverlay.Layers.FirstOrDefault() as RoutingLayer;
ContextMenuItemType contextMenuItem = GetContextMenuItemType(sender as ContextMenuItem);
switch (contextMenuItem)
{
case ContextMenuItemType.StartPoint:
startPoint.Text = string.Format("{0} , {1}", Math.Round(e.Location.X, 8), Math.Round(e.Location.Y, 8));
routingLayer.StartPoint = e.Location;
break;
case ContextMenuItemType.EndPoint:
endPoint.Text = string.Format("{0} , {1}", Math.Round(e.Location.X, 8), Math.Round(e.Location.Y, 8));
routingLayer.EndPoint = e.Location;
break;
case ContextMenuItemType.StopPoint:
stopItems.Add(new StopItem(e.Location) { Number = stopItems.Count });
routingLayer.StopPoints.Add(e.Location);
imgInvert.CssClass = "hideInvert";
stopItemList.DataSource = stopItems;
stopItemList.DataBind();
break;
}
routingLayer.Routes.Clear();
routingOverlay.Redraw();
}
}
private ContextMenuItemType GetContextMenuItemType(ContextMenuItem contextMenu)
{
ContextMenuItemType result = ContextMenuItemType.NoSure;
foreach (var item in contextMenuItems.Keys.Where(a => contextMenu.InnerHtml.Equals(contextMenuItems[a])))
{
result = (ContextMenuItemType)Enum.Parse(typeof(ContextMenuItemType), item);
}
return result;
}
private bool IdentifyAddressPointRestriction(PointShape addressPoint)
{
bool inRestriction = false;
ShapeFileFeatureLayer restrictedLayer = ((LayerOverlay)webMap.CustomOverlays["RestrictedOverlay"]).Layers["RestrictedLayer"] as ShapeFileFeatureLayer;
restrictedLayer.Open();
Collection<Feature> features = restrictedLayer.QueryTools.GetFeaturesContaining(addressPoint, ReturningColumnsType.NoColumns);
restrictedLayer.Close();
if (features.Count <= 0) // Drawn feature is out of the supported area (out of Frisco TX.)
{
// Show warning information when the drawn point locate out of restricted layer.
ScriptManager.RegisterStartupScript(mapContentPanel, mapContentPanel.GetType(), "Warning",
@"$('#outofBoundaryWarning').dialog('open');$('.ui-dialog-titlebar').hide();", true);
inRestriction = true;
}
return inRestriction;
}
private void UndoTrack()
{
if (newBarrierFeature != null)
{
LayerOverlay routingOverlay = webMap.CustomOverlays["RoutingOverlay"] as LayerOverlay;
InMemoryFeatureLayer barrierLayer = routingOverlay.Layers["BarrierLayer"] as InMemoryFeatureLayer;
barrierLayer.InternalFeatures.Remove(newBarrierFeature);
webMap.EditOverlay.Features.Remove(newBarrierFeature);
newBarrierFeature = null;
// Refresh the avoid feature ids.
avoidableFeatureIds.Clear();
foreach (Feature feature in barrierLayer.InternalFeatures)
{
BaseShape barrierShape = feature.GetShape();
routingShapeFile.Open();
Collection<Feature> features = routingShapeFile.FeatureSource.GetFeaturesWithinDistanceOf(barrierShape, webMap.MapUnit, DistanceUnit.Meter, 1, ReturningColumnsType.NoColumns);
routingShapeFile.Close();
foreach (Feature avoidableFeature in features)
{
avoidableFeatureIds.Add(avoidableFeature.Id);
}
}
routingOverlay.Redraw();
}
}
private void ClearBarriers()
{
LayerOverlay routingOverlay = webMap.CustomOverlays["RoutingOverlay"] as LayerOverlay;
InMemoryFeatureLayer barrierLayer = routingOverlay.Layers["BarrierLayer"] as InMemoryFeatureLayer;
barrierLayer.InternalFeatures.Clear();
avoidableFeatureIds.Clear();
webMap.EditOverlay.Features.Clear();
webMap.EditOverlay.TrackMode = TrackMode.None;
routingOverlay.Redraw();
}
private void DisplayDirectionsPath()
{
LayerOverlay routingOverlay = webMap.CustomOverlays["RoutingOverlay"] as LayerOverlay;
RoutingLayer routingLayer = routingOverlay.Layers.FirstOrDefault() as RoutingLayer;
if (routingLayer == null || routingLayer.StartPoint == null || routingLayer.EndPoint == null)
return;
DistanceUnit distanceUnit = ddlDistanceUnit.SelectedIndex == 0 ? DistanceUnit.Mile : DistanceUnit.Kilometer;
string rtgFilePathName = rblRouteMode.SelectedIndex == 0 ? rtgShortestFile : rtgFastestFile;
RoutingEngine routingEngine = new RoutingEngine(new RtgRoutingSource(MapPath(rtgFilePathName)), routingShapeFile.FeatureSource);
InMemoryFeatureLayer barrierLayer = routingOverlay.Layers["BarrierLayer"] as InMemoryFeatureLayer;
RoutePathAndDirection routePathAndDirection = new RoutePathAndDirection(routingEngine, routingLayer.StartPoint, routingLayer.EndPoint, barrierLayer.FeatureSource, avoidableFeatureIds, routingLayer.StopPoints);
// Get the routes.
RoutingResult result = routePathAndDirection.GetRoute();
// Refresh the route result.
routingLayer.Routes.Clear();
routingLayer.Routes.Add(result.Route);
Collection<RouteDirection> models = new Collection<RouteDirection>();
for (int i = 0; i < result.RouteSegments.Count; i++)
{
RouteDirection routeDirection = new RouteDirection(result.RouteSegments[i], result.Features[i], roadColumnName, webMap.MapUnit, distanceUnit);
models.Add(routeDirection);
}
repeaterQueryResult.DataSource = models;
repeaterQueryResult.DataBind();
routingOverlay.Redraw();
}
private void InitializeMapOverlays()
{
WorldMapKitWmsWebOverlay worldMapKitOverlay = new WorldMapKitWmsWebOverlay("World Map Kit");
worldMapKitOverlay.Projection = WorldMapKitProjection.DecimalDegrees;
webMap.CustomOverlays.Add(worldMapKitOverlay);
// Routing overlay.
var routingOverlay = new LayerOverlay("RoutingOverlay");
webMap.CustomOverlays.Add(routingOverlay);
var routingLayer = new RoutingLayer();
routingLayer.StartPointStyle = new PointStyle(new GeoImage(MapPath("/Images/start.png")));
routingLayer.EndPointStyle = new PointStyle(new GeoImage(MapPath("/Images/end.png")));
routingLayer.StopPointStyle = new PointStyle(new GeoImage(MapPath("/Images/stop.png"))) { YOffsetInPixel = -10 };
routingLayer.StopTextStyle.TextSolidBrush.Color = GeoColor.StandardColors.White;
routingLayer.StopTextStyle.Font = new GeoFont("Arial", 10);
routingLayer.XOffsetInPixelOfStopOrder = -3;
routingLayer.YOffsetInPixelOfStopOrder = 14;
routingOverlay.Layers.Add("RoutingLayer", routingLayer);
var barrierLayer = new InMemoryFeatureLayer();
barrierLayer.Open();
barrierLayer.Columns.Add(new FeatureSourceColumn("Barrier", "Charater", 10));
barrierLayer.ZoomLevelSet.ZoomLevel01.DefaultAreaStyle = AreaStyles.CreateSimpleAreaStyle(GeoColor.FromArgb(100, GeoColor.SimpleColors.Red), GeoColor.SimpleColors.Red, 1);
barrierLayer.ZoomLevelSet.ZoomLevel01.DefaultTextStyle = TextStyles.CreateSimpleTextStyle("Barrier", "Arial", 12, DrawingFontStyles.Regular, GeoColor.StandardColors.Black, GeoColor.SimpleColors.White, 2);
barrierLayer.ZoomLevelSet.ZoomLevel01.ApplyUntilZoomLevel = ApplyUntilZoomLevel.Level20;
routingOverlay.Layers.Add("BarrierLayer", barrierLayer);
// Restricted overlay
LayerOverlay restrictedOverlay = new LayerOverlay("RestrictedOverlay");
webMap.CustomOverlays.Add(restrictedOverlay);
ShapeFileFeatureLayer restrictedLayer = new ShapeFileFeatureLayer(MapPath(austinCountyShapeFile));
AreaStyle extentStyle = new AreaStyle();
extentStyle.CustomAreaStyles.Add(new AreaStyle(new GeoSolidBrush(GeoColor.SimpleColors.Transparent)) { OutlinePen = new GeoPen(GeoColor.SimpleColors.White, 5.5f) });
extentStyle.CustomAreaStyles.Add(new AreaStyle(new GeoSolidBrush(GeoColor.SimpleColors.Transparent)) { OutlinePen = new GeoPen(GeoColor.SimpleColors.Red, 1.5f) { DashStyle = LineDashStyle.Dash } });
restrictedLayer.ZoomLevelSet.ZoomLevel01.DefaultAreaStyle = extentStyle;
restrictedLayer.ZoomLevelSet.ZoomLevel01.ApplyUntilZoomLevel = ApplyUntilZoomLevel.Level20;
restrictedOverlay.Layers.Add("RestrictedLayer", restrictedLayer);
// Scale bar layer
ScaleBarAdornmentLayer scaleBarAdormentLayer = new ScaleBarAdornmentLayer();
scaleBarAdormentLayer.Location = AdornmentLocation.LowerLeft;
scaleBarAdormentLayer.XOffsetInPixel = 10;
webMap.AdornmentOverlay.Layers.Add("ScaleBar", scaleBarAdormentLayer);
}
private void InitializeMapContextMenu()
{
string startInnerHtml = @"<img src='/Images/start.png' class='routeMenuImg'><span class='routeMenuItem'>Directions from here</span>";
string endInnerHtml = @"<img src='/Images/end.png' class='routeMenuImg'><span class='routeMenuItem'>Directions to here</span>";
string stopInnerHtml = @"<img src='/Images/stop.png' class='routeMenuImg'><span class='routeMenuItem'>Add a waypoint here</span>";
ContextMenu menuOnMap = new ContextMenu("area", 180);
ContextMenuItem startItem = new ContextMenuItem(startInnerHtml, "routeMenu", "routeMenuSelected", "startRouteMenu");
ContextMenuItem endItem = new ContextMenuItem(endInnerHtml, "routeMenu", "routeMenuSelected", "endRouteMenu");
ContextMenuItem stopItem = new ContextMenuItem(stopInnerHtml, "routeMenu", "routeMenuSelected", "stopRouteMenu");
startItem.Click += MenuItemClick;
endItem.Click += MenuItemClick;
stopItem.Click += MenuItemClick;
menuOnMap.MenuItems.Add(startItem);
menuOnMap.MenuItems.Add(endItem);
menuOnMap.MenuItems.Add(stopItem);
contextMenuItems = new Dictionary<string, string>();
contextMenuItems.Add("StartPoint", startInnerHtml);
contextMenuItems.Add("EndPoint", endInnerHtml);
contextMenuItems.Add("StopPoint", stopInnerHtml);
webMap.ContextMenu = menuOnMap;
}
}
}