EOS/Scripts/out/files/Geo_positioningTool.js.html
Nidhi Bhargava f0c1ab20e1 code push
2025-09-04 16:25:07 +05:30

2458 lines
105 KiB
HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Geo\positioningTool.js</title>
<link rel="stylesheet" href="http://yui.yahooapis.com/3.9.1/build/cssgrids/cssgrids-min.css">
<link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
<link rel="stylesheet" href="../assets/css/main.css" id="site_styles">
<link rel="shortcut icon" type="image/png" href="../assets/favicon.png">
<script src="http://yui.yahooapis.com/combo?3.9.1/build/yui/yui-min.js"></script>
</head>
<body class="yui3-skin-sam">
<div id="doc">
<div id="hd" class="yui3-g header">
<div class="yui3-u-3-4">
<h1><img src="../assets/css/logo.png" title=""></h1>
</div>
<div class="yui3-u-1-4 version">
<em>API Docs for: </em>
</div>
</div>
<div id="bd" class="yui3-g">
<div class="yui3-u-1-4">
<div id="docs-sidebar" class="sidebar apidocs">
<div id="api-list">
<h2 class="off-left">APIs</h2>
<div id="api-tabview" class="tabview">
<ul class="tabs">
<li><a href="#api-classes">Classes</a></li>
<li><a href="#api-modules">Modules</a></li>
</ul>
<div id="api-tabview-filter">
<input type="search" id="api-filter" placeholder="Type to filter APIs">
</div>
<div id="api-tabview-panel">
<ul id="api-classes" class="apis classes">
<li><a href="../classes/CallFeedbackRating.html">CallFeedbackRating</a></li>
<li><a href="../classes/CloseTicketReport.html">CloseTicketReport</a></li>
<li><a href="../classes/ConsolidatedReport.html">ConsolidatedReport</a></li>
<li><a href="../classes/CustomerReport.html">CustomerReport</a></li>
<li><a href="../classes/DealerWiseCallDetails.html">DealerWiseCallDetails</a></li>
<li><a href="../classes/DeclinedCalls.html">DeclinedCalls</a></li>
<li><a href="../classes/DropDownData.html">DropDownData</a></li>
<li><a href="../classes/EicherPromise.html">EicherPromise</a></li>
<li><a href="../classes/EosCallCount.html">EosCallCount</a></li>
<li><a href="../classes/GeoAnalysis.html">GeoAnalysis</a></li>
<li><a href="../classes/HdBusLmdContrCallFeedbackRatingibution.html">HdBusLmdContrCallFeedbackRatingibution</a></li>
<li><a href="../classes/HdBusLmdContribution.html">HdBusLmdContribution</a></li>
<li><a href="../classes/HistoryTracking.html">HistoryTracking</a></li>
<li><a href="../classes/LiveTracking.html">LiveTracking</a></li>
<li><a href="../classes/ManageEscalation.html">ManageEscalation</a></li>
<li><a href="../classes/ManageFleet.html">ManageFleet</a></li>
<li><a href="../classes/ManageFleet_Detail.html">ManageFleet_Detail</a></li>
<li><a href="../classes/ManageFleet_details.html">ManageFleet_details</a></li>
<li><a href="../classes/ManageOwner.html">ManageOwner</a></li>
<li><a href="../classes/ManageReason.html">ManageReason</a></li>
<li><a href="../classes/ManageVechile.html">ManageVechile</a></li>
<li><a href="../classes/ManageVehicle.html">ManageVehicle</a></li>
<li><a href="../classes/NonVecvUserManagement.html">NonVecvUserManagement</a></li>
<li><a href="../classes/Notifications.html">Notifications</a></li>
<li><a href="../classes/OpenTicketReport.html">OpenTicketReport</a></li>
<li><a href="../classes/OrganizationChart.html">OrganizationChart</a></li>
<li><a href="../classes/PositioningTool.html">PositioningTool</a></li>
<li><a href="../classes/PositioningTool_Report.html">PositioningTool_Report</a></li>
<li><a href="../classes/ReasonForClosure.html">ReasonForClosure</a></li>
<li><a href="../classes/Report.html">Report</a></li>
<li><a href="../classes/ShowDealerMap.html">ShowDealerMap</a></li>
<li><a href="../classes/TicketAdministration.html">TicketAdministration</a></li>
<li><a href="../classes/TicketAdministration_FullDetail.html">TicketAdministration_FullDetail</a></li>
<li><a href="../classes/TicketFeedback.html">TicketFeedback</a></li>
<li><a href="../classes/TicketForDealer.html">TicketForDealer</a></li>
<li><a href="../classes/TicketForDealer_FullDetails.html">TicketForDealer_FullDetails</a></li>
<li><a href="../classes/TicketReassign.html">TicketReassign</a></li>
<li><a href="../classes/TileDashboard.html">TileDashboard</a></li>
<li><a href="../classes/TimeSlotClosure.html">TimeSlotClosure</a></li>
<li><a href="../classes/TollFreeAndOpportunityLoss.html">TollFreeAndOpportunityLoss</a></li>
<li><a href="../classes/VanCoverageDesigner.html">VanCoverageDesigner</a></li>
<li><a href="../classes/VecvUserManagement.html">VecvUserManagement</a></li>
</ul>
<ul id="api-modules" class="apis modules">
<li><a href="../modules/Dashboard.html">Dashboard</a></li>
<li><a href="../modules/DropDownData.html">DropDownData</a></li>
<li><a href="../modules/Geo.html">Geo</a></li>
<li><a href="../modules/Inventory.html">Inventory</a></li>
<li><a href="../modules/Notifications.html">Notifications</a></li>
<li><a href="../modules/ReportModule.html">ReportModule</a></li>
<li><a href="../modules/Ticket.html">Ticket</a></li>
<li><a href="../modules/TrackingModule.html">TrackingModule</a></li>
<li><a href="../modules/UserManagement.html">UserManagement</a></li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="yui3-u-3-4">
<div id="api-options">
Show:
<label for="api-show-inherited">
<input type="checkbox" id="api-show-inherited" checked>
Inherited
</label>
<label for="api-show-protected">
<input type="checkbox" id="api-show-protected">
Protected
</label>
<label for="api-show-private">
<input type="checkbox" id="api-show-private">
Private
</label>
<label for="api-show-deprecated">
<input type="checkbox" id="api-show-deprecated">
Deprecated
</label>
</div>
<div class="apidocs">
<div id="docs-main">
<div class="content">
<h1 class="file-heading">File: Geo\positioningTool.js</h1>
<div class="file">
<pre class="code prettyprint linenums">
/*================================================================================================================\
+
+ Project : GODATA-VCEV
+ Filename : positioningTool.js
+ Module Name : Positioning Tool + Blind Spot
+ Purpose : To show all Vans and their respective reachable points geographically. And draw paths between them.
+ One can move van and its points and save that state.
+ Blind Spot - Show blind spot geographically and suggest new van on map to cover all the area.
+ One is able to put a dummy van on the map to check if the path strech is covered or not.
+ Coded By : Pankaj Khandal
+
+================================================================================================================*/
/**
* To show position of vans, reposition them and generate BlindSpot on a path.
* @module Geo
*/
/**
* To show position of vans, reposition them and generate BlindSpot on a path.
* @class PositioningTool
* @constructor
*/
//================= Global variables===============================
/**
* Global References: Initializing global stores for markers, images, icons, enable/disable bits etc.
* @for PositioningTool
*/
var vanImagePath = &quot;../../Content/css/images/avil-van.png&quot;,
vanReachablePointImagePath = &quot;../../Scripts/map_api/icons/red_circle.png&quot;,
bs_vanImagePath = &quot;../../Content/css/images/avil-van.png&quot;,
bs_waypointImagePath = &quot;../../Scripts/map_api/icons/green_circle.png&quot;,
bs_vanToolImagePath = &quot;../../Content/css/images/avil-van-pointing.png&quot;,
bs_waypointToolImagePath = &quot;../../Scripts/map_api/icons/green_circle-pointing.png&quot;,
bs_downArrowImagePath = &quot;../../Scripts/map_api/icons/arrow01.png&quot;,
markerTransImgPath = &quot;../../Scripts/map_api/icons/red_blink.gif&quot;,
defaultLat = 26.912285124827,
defaultLng = 75.7873203125;
var SecurityToken, utcMinutes, UserId;
var map = null; // to store map object globally
var directionService; // to store Direction-Service object globally
var geoCoder; // to store Geo-Coder object globally
var distanceMatrixService; // to store Distance-Matrix Service object globally
var MARKERS = []; // To store Marker objects globally
var POLYGONS = []; // To store Polygon object globally
var POSITIONING_JSON = []; // To store Exiting Positionig JSON globally
var UPDATED_POSITIONING_JSON = []; // To store updated coverage Objects
var ROUTES = []; // To store route objects globally
var MOVED_VAN_ROUTES = []; // To store dragged Van route object globally
var distanceTimeObj = new Object(); // To store the callback result of Distance Matrix.
var directionMatrixTime = 0; // To hold new reachable time when we drag a reachable point
var directionObj = {}; // To store Route-Direction Objects
var directionsRenderer; // To store direction display renderer on map
var latlngbounds; // To store lat long bounds to center the map
var pointAngle = 30; // Angle on which we want a point from a sorce point (Degree)
var bs_pointAngle = 30; // Angle on which we want a point from a sorce point (Degree)
var radiusIncrement = 15; // constant increament in radius to get optimal reachable point from a van
var radiusAccToSlaObj = { &#x27;90&#x27;: 55, &#x27;120&#x27;: 75 }; // Van&#x27;s reachable point&#x27;s minimum distance (KMs) for diffrent SLAs in minutes
var slaTimeInMin = 0; // To store SLA time in minutes globally
var coverageMultiplier = 1.6; // Coverage enhancer
var enableCoverageDesign = true; // To enable/disable coverage.
var coverageDesiged = false; // To check if coverage is designed once
//-------------- BLIND SPOT Global variables ----------------------
var BS_WAYPOINDID = 0; // Initialize the waypoint Id
var BS_VAN_ID = 0; // Initialize the Van Id
var disable_map_click_Listener = true; // To disable/enable map click
var disable_map_mousemove_Listener_waypoint = true; // To disable/enable mouse move on map
var disable_map_click_Listener_waypoint = true; // To disable/enable map click for a waypoint
var disable_map_click_Listener_van = true; // To disable/enable map click for a van
var disable_map_mousemove_Listener_van = true; //To disable/enable mouse move on map for van
var enableBlindSpotGenerator = true; // To disable/enable Blind spot generation
var bs_enableCoverageDesign = true; // To disable/enable coverage designer
var bs_popTheVanOut = true; // To disable/enable removing the last van marker, when no response from goole
var bs_coverageMultiplier = 1.6; // covearge enhancer
var bs_coverageDesiged = false; // To disable/enable if coverage is designed
var BS_MARKERS = []; // To Store Blind Spot markers globally
var BS_VAN_MARKERS = []; // To Store Blind Spot Van markers globally
var BS_WAYPOINTS = []; // To Store Blind Spot waypoints globally
var BS_WAYPOINTS_reverse = []; // To Store Blind Spot waypoints in reverse order of plotting
var BS_ENDS = []; // To Store Blind Spot region End points
var BS_STARTS = []; // To Store Blind Spot region start points
var BS_CIRCLES = []; // To Store Blind Spot region circles
var BS_MID_MARKERS = []; // To Store Blind Spot region mid points
var BS_MOVED_VAN_ROUTES = []; // To Store Blind Spot moved van route object
var BS_POLYGONS = []; // To Store Blind Spot polygons
var bs_directionObj = {}; // To Store Blind Spot Van&#x27;s routes to their reachable points
var BS_ARROW_MARKERS = []; // To Store Blind Spot region arrow markers
var BS_VAN_REACHABLE_POINT = []; // To Store Blind Spot Van&#x27;s reachable points
var BS_ROUTES = []; // To Store Blind Spot Van&#x27;s routes
//--------------------------------------------
//=================================================================
/**
* To check state is entered or not.
* @method StateValid
* @for PositioningTool
*/
function StateValid() {
var vResult = false;
var State = $(&quot;#stateCombobox&quot;).val();
$(&quot;#spanState1&quot;).hide();
if (State == &quot;&quot;) {
$(&quot;#spanState1&quot;).show();
}
else {
vResult = true;
}
return vResult;
}
/////============================= Getting Circular points which is some time away from a source point =====================
/**
* To convert a degrees into radians.
* @method Number.prototype.toRad
* @for PositioningTool
*/
Number.prototype.toRad = function () {
return this * Math.PI / 180;
}
/**
* To convert a radians into degrees.
* @method Number.prototype.toDeg
* @for PositioningTool
*/
Number.prototype.toDeg = function () {
return this * 180 / Math.PI;
}
/**
* To get a position at an angle and at a distance on google map.
* @method google.maps.LatLng.prototype.destinationPoint
* @param {Number} angle angle in Degrees
* @param {Number} dist distance in KMs
* @for PositioningTool
*/
google.maps.LatLng.prototype.destinationPoint = function (angle, dist) {
dist = dist / 6371;
angle = angle.toRad();
var lat1 = this.lat().toRad(), lon1 = this.lng().toRad();
var lat2 = Math.asin(Math.sin(lat1) * Math.cos(dist) + Math.cos(lat1) * Math.sin(dist) * Math.cos(angle));
var lon2 = lon1 + Math.atan2(Math.sin(angle) * Math.sin(dist) * Math.cos(lat1), Math.cos(dist) - Math.sin(lat1) * Math.sin(lat2));
if (isNaN(lat2) || isNaN(lon2)) return null;
return new google.maps.LatLng(lat2.toDeg(), lon2.toDeg());
}
/**
* To get a position at an angle and at a distance on google map.
* @method findReachablePointsForVan
* @param {Object} sourcePosition position(lat-long object) of source
* @param {Number} pointAngle angle in Degrees
* @param {Number} radius distance in KMs
* @for PositioningTool
*/
function findReachablePointsForVan(sourcePosition, pointAngle, radius) {
var reachablePoints = [];
for (var i = 0; i &lt;= 360; i = i + pointAngle) {
var point = sourcePosition.destinationPoint(i, radius);
reachablePoints.push(point);
}
return reachablePoints;
}
/////================================================================================================================
//================== FILTERS Section Start =========================
/**
* To populate state combobox.
* @method loadStateChoices
* @for PositioningTool
*/
function loadStateChoices() {
SecurityToken = securityToken;
utcMinutes = parseInt(UtcMinutes, 10);
UserId = userId;
$.ajax({
type: &quot;POST&quot;,
url: WCFRESTURL.GetStateListIdWise,
data: { Token: SecurityToken, UtcMinutes: utcMinutes, UserId: UserId },
dataType: &quot;json&quot;,
success: function (data) {
$(&quot;#stateCombobox&quot;).kendoComboBox({
placeholder: &quot;State&quot;,
dataTextField: &quot;StateAlias&quot;,
dataValueField: &quot;StateId&quot;,
filter: &quot;contains&quot;,
dataSource: data,
change: function () {
// loading cities according to state id
//loadCityChoices($(&quot;#stateCombobox&quot;).val());
//loadDealerChoices($(&quot;#stateCombobox&quot;).data(&quot;kendoComboBox&quot;).text(), $(&quot;#cityCombobox&quot;).data(&quot;kendoComboBox&quot;).text());
}
});
},
complete: function () {
//$(&quot;#stateCombobox&quot;).data(&#x27;kendoComboBox&#x27;).select(0);
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
}
/**
* To populate city combobox.
* @method loadCityChoices
* @for PositioningTool
*/
function loadCityChoices(stateId) {
SecurityToken = securityToken;
utcMinutes = parseInt(UtcMinutes, 10);
UserId = userId;
$.ajax({
type: &quot;POST&quot;,
url: WCFRESTURL.GetCityListStateIdWise,
data: { Token: SecurityToken, UtcMinutes: utcMinutes, UserId: UserId, StateId: stateId },
dataType: &quot;json&quot;,
success: function (data) {
$(&quot;#cityCombobox&quot;).kendoComboBox({
dataTextField: &quot;CityName&quot;,
dataValueField: &quot;CityId&quot;,
filter: &quot;contains&quot;,
dataSource: data,
change: function () {
loadDealerChoices($(&quot;#stateCombobox&quot;).data(&quot;kendoComboBox&quot;).text(), $(&quot;#cityCombobox&quot;).data(&quot;kendoComboBox&quot;).text());
}
});
},
complete: function () {
$(&quot;#cityCombobox&quot;).data(&quot;kendoComboBox&quot;).text(&#x27;&#x27;);
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
}
/**
* To populate city combobox.
* @method loadCityChoices
* @for PositioningTool
*/
function loadDealerChoices(state, city) {
SecurityToken = securityToken;
utcMinutes = parseInt(UtcMinutes, 10);
UserId = userId;
$.ajax({
type: &quot;POST&quot;,
url: WCFRESTURL.GetDealerStateCityWise,
data: { Token: SecurityToken, UtcMinutes: utcMinutes, UserId: UserId, DealerStateParam: state, DealerCityParam: city },
dataType: &quot;json&quot;,
success: function (data) {
$(&quot;#dealerCombobox&quot;).kendoComboBox({
dataTextField: &quot;DealerDealerName&quot;,
dataValueField: &quot;DealerId&quot;,
filter: &quot;contains&quot;,
dataSource: data,
});
},
complete: function () {
$(&quot;#dealerCombobox&quot;).data(&quot;kendoComboBox&quot;).text(&#x27;&#x27;);
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
}
/**
* To populate SLA combobox.
* @method loadAllSla
* @for PositioningTool
*/
function loadAllSla() {
SecurityToken = securityToken;
utcMinutes = parseInt(UtcMinutes, 10);
UserId = userId;
$.ajax({
type: &quot;POST&quot;,
url: WCFRESTURL.GetAllSLA,
data: { Token: SecurityToken, UtcMinutes: utcMinutes, UserId: UserId },
dataType: &quot;json&quot;,
success: function (data) {
$(&quot;#slaCombobox&quot;).kendoDropDownList({
dataTextField: &quot;SlaTime&quot;,
dataValueField: &quot;Id&quot;,
dataSource: data,
index: 0,
change: function () {
// Getting curent SLA time and storing that globally
slaTimeInMin = $(&quot;#slaCombobox&quot;).data(&quot;kendoDropDownList&quot;).text();
}
});
},
complete: function () {
// Getting curent SLA time and storing that globally
slaTimeInMin = $(&quot;#slaCombobox&quot;).data(&quot;kendoDropDownList&quot;).text();
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
}
//================== FILTERS Section End =========================
/**
* To create unique Van-JSON to update on the server.
* @method createUpdatedPOSITIONING_JSON
* @param {Object} van van-object contains van and its reachable point details.
* @for PositioningTool
*/
function createUpdatedPOSITIONING_JSON(van) {
if (UPDATED_POSITIONING_JSON.length == 0) {
UPDATED_POSITIONING_JSON.push(van);
}
else {
for (var i = 0; i &lt; UPDATED_POSITIONING_JSON.length; i++) {
if (UPDATED_POSITIONING_JSON[i].VanId == van.VanId) {
UPDATED_POSITIONING_JSON.splice(i, 1);
UPDATED_POSITIONING_JSON.push(van);
} else {
UPDATED_POSITIONING_JSON.push(van);
}
}
}
}
/**
* To update the Van coverage onto the server.
* @method updateVanCoverage
* @for PositioningTool
*/
function updateVanCoverage() {
$(&quot;#div_load&quot;).show(); // Showing loading
SecurityToken = securityToken;
utcMinutes = parseInt(UtcMinutes, 10);
UserId = userId;
var updatedVanCoverageData = JSON.stringify(UPDATED_POSITIONING_JSON); // serializing the JSON before sending to the server
$.ajax({
url: WCFRESTURL.UpdateAllVansOnGeoView,
type: &quot;POST&quot;,
data: { Token: &quot;teramatrix&quot;, VanListJson: updatedVanCoverageData },
dataType: &quot;json&quot;,
contentType: &quot;application/x-www-form-urlencoded; charset=utf-8&quot;, // This is the content type when posting Plain Text to server.
success: function (data) {
$(&#x27;#get_van_coverage&#x27;).show(); // Showing the get-van-coverage button
$(&#x27;#update_van_coverage&#x27;).hide(); // Hiding update-van-coverage button
$(&#x27;#reset_van_coverage&#x27;).hide(); // Hiding update-van-coverage button
jAlert(POSITIONING_MSG[&#x27;coverage_update_success&#x27;], &#x27;Message&#x27;);
},
complete: function () {
$(&quot;#div_load&quot;).hide(); // Hiding loading
UPDATED_POSITIONING_JSON = []; // Making the updated positioning JSON empty. so that it is less occupied next time when update is happening
},
error: function (jqXHR, textStatus, errorThrown) {
jAlert(POSITIONING_MSG[&#x27;coverage_update_error&#x27;], &#x27;Message&#x27;);
}
});
}
/**
* To Reset the Van server to earliar state.
* @method resetVanCoverage
* @for PositioningTool
*/
function resetVanCoverage() {
getAllVansOnGeoView();
}
/**
* To get distance and time to raech to a point on google map and store that in a global object.
* @method getDistanceAndTime
* @param {Double} sourceLat source lattitude
* @param {Double} sourceLong source longitude
* @param {Double} destinationLat destination lattitude
* @param {Double} destinationLong destination longitude
* @for PositioningTool
*/
function getDistanceAndTime(sourceLat, sourceLong, destinationLat, destinationLong) {
var sourceLocation = new google.maps.LatLng(sourceLat, sourceLong);
var destinationLocation = new google.maps.LatLng(destinationLat, destinationLong);
var request = {
origins: [sourceLocation],
destinations: [destinationLocation],
travelMode: google.maps.TravelMode.DRIVING,
//transitOptions: google.maps.TransitMode.BUS,
unitSystem: google.maps.UnitSystem.METRIC,
//durationInTraffic: Boolean, // consider traffice conditions //for work customers
avoidHighways: false,
avoidTolls: false
}
distanceMatrixService.getDistanceMatrix(request, function (response, status) {
if (status == google.maps.DistanceMatrixStatus.OK) {
var result = response.rows[0].elements[0];
var distance = result.distance.text;
var duration = result.duration.value;
// Setting the gloabal object to store the duration.
distanceTimeObj.distance = distance;
distanceTimeObj.durationInMin = parseInt(duration / 60);
directionMatrixTime = parseInt(duration / 60);
}
});
}
/**
* To get circular points at a distance and at an angle.
* @method getCoverageForVan
* @param {Double} newLatOfVan marker&#x27;s new lattitude
* @param {Double} newLongOfVan marker&#x27;s new longitude
* @param {Int} slaTimeInMin SLA time in minutes
* @param {Int} minRadius minimum radius
* @for PositioningTool
*/
function getCoverageForVan(newLatOfVan, newLongOfVan, slaTimeInMin) {
var vanLocation = new google.maps.LatLng(newLatOfVan, newLongOfVan);
//minRadius = (slaTimeInMin == 90) ? (minRadius = minRadiusFor90min) : (minRadius = minRadiusFor120min);
minRadius = radiusAccToSlaObj[slaTimeInMin];
var radiusArray = [];
radiusArray.push(minRadius);
radiusArray.push(minRadius + radiusIncrement);
radiusArray.push(minRadius + (2 * radiusIncrement));
radiusArray.push(minRadius + (3 * radiusIncrement));
var points = [];
for (var angle = 0; angle &lt; 360; angle += pointAngle) {
for (var i = 0; i &lt; radiusArray.length; i++) {
var point = vanLocation.destinationPoint(angle, radiusArray[i]);
points.push(point);
}
}
return points;
}
/**
* To get circular points at a distance and at an angle.
* @method getCoverageForVanStatic
* @param {Double} newLatOfVan marker&#x27;s new lattitude
* @param {Double} newLongOfVan marker&#x27;s new longitude
* @param {Int} slaTimeInMin SLA time in minutes
* @param {Int} minRadius minimum radius
* @for PositioningTool
*/
function getCoverageForVanStatic(newLatOfVan, newLongOfVan, slaTimeInMin) {
var vanLocation = new google.maps.LatLng(newLatOfVan, newLongOfVan);
//minRadius = (slaTimeInMin == 90) ? (minRadius = minRadiusFor90min) : (minRadius = minRadiusFor120min);
minRadius = radiusAccToSlaObj[slaTimeInMin];
var radiusArray = [];
radiusArray.push(minRadius);
var points = [];
for (var angle = 0; angle &lt; 360; angle += pointAngle) {
for (var i = 0; i &lt; radiusArray.length; i++) {
var point = vanLocation.destinationPoint(angle, radiusArray[i]);
points.push(point);
}
}
return points;
}
/**
* To get circular points at a distance and at an angle.
* @method bs_getCoverageForVan
* @param {Double} newLatOfVan marker&#x27;s new lattitude
* @param {Double} newLongOfVan marker&#x27;s new longitude
* @param {Int} slaTimeInMin SLA time in minutes
* @param {Int} minRadius minimum radius
* @for PositioningTool
*/
function bs_getCoverageForVan(newLatOfVan, newLongOfVan, slaTimeInMin) {
var vanLocation = new google.maps.LatLng(newLatOfVan, newLongOfVan);
//minRadius = (slaTimeInMin == 90) ? (minRadius = minRadiusFor90min) : (minRadius = minRadiusFor120min);
minRadius = radiusAccToSlaObj[slaTimeInMin];
var radiusArray = [];
radiusArray.push(minRadius);
radiusArray.push(minRadius + radiusIncrement);
radiusArray.push(minRadius + (2 * radiusIncrement));
radiusArray.push(minRadius + (3 * radiusIncrement));
var points = [];
for (var angle = 0; angle &lt; 360; angle += bs_pointAngle) {
for (var i = 0; i &lt; radiusArray.length; i++) {
var point = vanLocation.destinationPoint(angle, radiusArray[i]);
points.push(point);
}
}
return points;
}
/**
* To get circular points at a distance and at an angle.
* @method bs_getCoverageForVanStatic
* @param {Double} newLatOfVan marker&#x27;s new lattitude
* @param {Double} newLongOfVan marker&#x27;s new longitude
* @param {Int} slaTimeInMin SLA time in minutes
* @param {Int} minRadius minimum radius
* @for PositioningTool
*/
function bs_getCoverageForVanStatic(newLatOfVan, newLongOfVan, slaTimeInMin) {
var vanLocation = new google.maps.LatLng(newLatOfVan, newLongOfVan);
//minRadius = (slaTimeInMin == 90) ? (minRadius = minRadiusFor90min) : (minRadius = minRadiusFor120min);
minRadius = radiusAccToSlaObj[slaTimeInMin];
var radiusArray = [];
radiusArray.push(minRadius);
var points = [];
for (var angle = 0; angle &lt; 360; angle += bs_pointAngle) {
for (var i = 0; i &lt; radiusArray.length; i++) {
var point = vanLocation.destinationPoint(angle, radiusArray[i]);
points.push(point);
}
}
return points;
}
/**
* To set the map center on the passed addess.
* @method setMapCenterToAddress
* @param {String} address address for the map
* @for PositioningTool
*/
function setMapCenterToAddress(address) {
geoCoder = new google.maps.Geocoder();
geoCoder.geocode({ &#x27;address&#x27;: address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
if (typeof results[0].geometry.bounds === &#x27;undefined&#x27;) {
map.fitBounds(results[0].geometry.bounds);
}
}
});
}
/**
* To draw the circle on the map.
* @method drawCircle
* @param {Object} center center of circle
* @param {Int} radius radius of circle
* @param {String} circleTitle title of circle
* @for PositioningTool
*/
function drawCircle(center, radius, circleTitle) {
var circleOptions = {
strokeColor: &#x27;#FF0000&#x27;,
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: &#x27;#FF0000&#x27;,
fillOpacity: 0.35,
map: map,
center: center,
radius: radius,
circleTitle: circleTitle
};
var circle = new google.maps.Circle(circleOptions);
return circle;
}
/**
* To get the midpoint between two points at a distance.
* @method getMidpoint
* @param {Array} points source and destionation points
* @param {Int} midpointDistance midpoint distance from a point
* @for PositioningTool
*/
function getMidpoint(points, midpointDistance) {
var tempDistance = midpointDistance;
var midpointLatLng;
// We go through each segment of the line
for (var i = 0; i &lt; points.length - 1; i++) {
var segment = points.slice(i, i + 2);
var length = google.maps.geometry.spherical.computeLength(segment);
tempDistance = tempDistance - length;
// If we&#x27;re at zero or below, we&#x27;ve found the line where our midpoint exists
if (tempDistance &lt;= 0) {
// We&#x27;ve gone past the midpoint so we need to back up.
var midpointLength = tempDistance + length;
// The proportion of the current segment where our midpoint exists
var percentage = midpointLength / length;
midpointLatLng = google.maps.geometry.spherical.interpolate(segment[0], segment[1], percentage);
break;
}
}
if (typeof midpointLatLng === &#x27;undefined&#x27;) {
// we don&#x27;t have a midpoint for this polyline, something went very wrong
return false;
} else {
return midpointLatLng;
}
}
////======================== Event / Action Handlers on Map Section Start ===========================
/**
* To plot van at new position and draw its coverage and paths
* @method dragEndHandlerForVan
* @param {Object} marker van marker object on map
* @for PositioningTool
*/
function dragEndHandlerForVanStatic(marker) {
//$(&quot;#div_load&quot;).show(); // Showing loading
//$(&#x27;#get_van_coverage&#x27;).hide(); // Hiding the get-van-coverage button
//$(&#x27;#update_van_coverage&#x27;).show(); // Showing update-van-coverage button
//$(&#x27;#reset_van_coverage&#x27;).show(); // Showing update-van-coverage button
var vanId = marker.id; // Getting Van id form the marker
MOVED_VAN_ROUTES = []; // Making the Moved-Van-Routes array empty.
//enableCoverageDesign = true; // enabling coverage design functionality
var newLatOfVan = marker.position.lat(); // getting lat of dragged marker
var newLongOfVan = marker.position.lng(); // getting long of dragged marker
// Getting Van reachable points at a given radius
var final_vanReachablePoints = getCoverageForVanStatic(newLatOfVan, newLongOfVan, slaTimeInMin);
coverageDesiged = true; // Coverage is desgned now
//---------------------------------------------------------------
// Plotting van, paths and updating van object
var sourceVan = new google.maps.LatLng(newLatOfVan, newLongOfVan);
// Plotting VAN&#x27;s reachable points
$.each(POSITIONING_JSON, function (index, van) {
if (van.VanId == vanId) {
deletePolygon(vanId); // Deleting the dragged Polygon
polyCoordinates = []; // taking empty array to store polygon coordinates
van.VanDefaultLatitude = newLatOfVan; // setting new lat to the Global JSON
van.VanDefaultLongitude = newLongOfVan; // setting new long to the Global JSON
// Remove previous polygon basis on &quot;title&quot;
for (var i = 0; i &lt; POLYGONS.length; i++) {
if (POLYGONS[i].title == van.VanId) {
POLYGONS[i].setMap(null);
POLYGONS.splice(i, 1);
}
}
// Plotting VAN&#x27;s reachable points
$.each(van.VanPostionList, function (point_index, point) {
var vanReachablePointId = point.VanPositionCoverageVanId + &#x27;_&#x27; + point.VanPositionCoverageId;
// One by one deleting route associated to this Van
deleteRoute(vanReachablePointId);
// One by one deleting VanReachable Points
deleteMarker(vanReachablePointId);
// if no point is there then set lat long to null
if (typeof final_vanReachablePoints[point_index] === &#x27;undefined&#x27;) {
// updating the Lat-Long of dragged item
point.VanPositionCoverageVanLatitude = null;
point.VanPositionCoverageVanLongitude = null;
}
else {
// updating the Lat-Long of dragged item
point.VanPositionCoverageVanLatitude = final_vanReachablePoints[point_index].lat();
point.VanPositionCoverageVanLongitude = final_vanReachablePoints[point_index].lng();
var reachablePointId = point.VanPositionCoverageVanId + &#x27;_&#x27; + point.VanPositionCoverageId;
var vanPointInfoWindow = &#x27;&lt;div&gt;&#x27; + reachablePointId + &#x27;&lt;/div&gt;&#x27;;
putMarkerOnMap(map, vanPointInfoWindow, point.VanPositionCoverageVanLatitude, point.VanPositionCoverageVanLongitude, &#x27;&#x27;, reachablePointId, vanReachablePointImagePath, true, false, false)
// Storing Point Cordinaates to draw a polygon
var reachablePoint = new google.maps.LatLng(point.VanPositionCoverageVanLatitude, point.VanPositionCoverageVanLongitude);
polyCoordinates.push(reachablePoint);
// craeting Route Object and storing that globally.
var routeObj = new Object({ &#x27;routeId&#x27;: reachablePointId, &#x27;source&#x27;: sourceVan, &#x27;destination&#x27;: reachablePoint });
MOVED_VAN_ROUTES.push(routeObj);
}
});
// Draw polygon and storing them globally
var polygon = drawPolygon(polyCoordinates, van.VanId);
POLYGONS.push(polygon);
// Drawing path for moved Van.
drawPathManagerForMovedVan();
// Creating Updated POSITIONING_JSON
createUpdatedPOSITIONING_JSON(van);
return;
}
});
//-------------------------------------------------
}
/**
* To plot van at new position and draw its coverage and paths
* @method dragEndHandlerForVan
* @param {Object} marker van marker object on map
* @for PositioningTool
*/
function dragEndHandlerForVan(marker) {
$(&quot;#div_load&quot;).show(); // Showing loading
$(&#x27;#get_van_coverage&#x27;).hide(); // Hiding the get-van-coverage button
$(&#x27;#update_van_coverage&#x27;).show(); // Showing update-van-coverage button
$(&#x27;#reset_van_coverage&#x27;).show(); // Showing update-van-coverage button
var vanId = marker.id; // Getting Van id form the marker
MOVED_VAN_ROUTES = []; // Making the Moved-Van-Routes array empty.
coverageDesiged = false; // Coverage is not there on map for this van
enableCoverageDesign = true; // enabling coverage design functionality
var newLatOfVan = marker.position.lat(); // getting lat of dragged marker
var newLongOfVan = marker.position.lng(); // getting long of dragged marker
// Getting Van reachable points at a given radius
var vanReachablePoints = getCoverageForVan(newLatOfVan, newLongOfVan, slaTimeInMin);
//--------------------------------------------
// Dividing reachable points array into two parts to send two saparate requests on direction matrix
var vanReachablePoints1 = [];
var vanReachablePoints2 = [];
var mid = parseInt(vanReachablePoints.length / 2);
for (var i = 0; i &lt; mid ; i++) {
vanReachablePoints1.push(vanReachablePoints[i])
vanReachablePoints2.push(vanReachablePoints[mid + i]);
}
//--------------------------------------------
var final_vanReachablePoints = [];
//================== Design Coverage =====================
// getting first 180 degree optimal points
setTimeout(function () {
var request1 = {
origins: [marker.position],
destinations: vanReachablePoints1,
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}
distanceMatrixService.getDistanceMatrix(request1, function (response, status) {
if (status == google.maps.DistanceMatrixStatus.OK) {
var result = response.rows[0].elements;
var start = 1;
var counter = 0;
for (var index1 = 0; index1 &lt; result.length; index1++) {
// putting van on its previous location when undefined response from direction matrix
if (typeof result[index1].duration === &#x27;undefined&#x27;) {
// Repositioning the marker to the last eligible location
//$.each(POSITIONING_JSON, function (i, van) {
// if (van.VanId == vanId) {
// marker.setPosition(new google.maps.LatLng(van.VanDefaultLatitude, van.VanDefaultLongitude));
// }
//});
//jAlert(POSITIONING_MSG[&#x27;drag_van_error&#x27;], &#x27;Message&#x27;);
dragEndHandlerForVanStatic(marker);
enableCoverageDesign = false; // disabling van coverage design
//$(&quot;#div_load&quot;).hide(); // hiding loading
return;
};
// getting and converting duration in minutes
var durationInMin = parseInt(result[index1].duration.value / 60, 10);
counter++;
if ((durationInMin &gt; (slaTimeInMin * bs_coverageMultiplier)) || (counter == 4)) {
((index1 - 1) == -1) ? final_vanReachablePoints.push(vanReachablePoints1[index1]) : final_vanReachablePoints.push(vanReachablePoints1[index1 - 1]);
index1 = start * 4;
start++;
counter = 0;
}
}
}
});
}, 300);
//--------------------------------
// getting 180-360 degree optimal points
setTimeout(function () {
if (coverageDesiged) { return; } // If coverage is designed once then exit the loop
var request2 = {
origins: [marker.position],
destinations: vanReachablePoints2,
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}
distanceMatrixService.getDistanceMatrix(request2, function (response, status) {
if (status == google.maps.DistanceMatrixStatus.OK) {
var result = response.rows[0].elements;
var start = 1;
var counter = 0;
for (var index2 = 0; index2 &lt; result.length; index2++) {
// putting van on its previous location when undefined response from direction matrix
if ((enableCoverageDesign == true) &amp;&amp; (typeof result[index2].duration === &#x27;undefined&#x27;)) {
// Repositioning the marker to the last eligible location
//$.each(POSITIONING_JSON, function (i, van) {
// if (van.VanId == vanId) {
// marker.setPosition(new google.maps.LatLng(van.VanDefaultLatitude, van.VanDefaultLongitude));
// }
//});
//jAlert(POSITIONING_MSG[&#x27;drag_van_error&#x27;], &#x27;Message&#x27;);
dragEndHandlerForVanStatic(marker);
//$(&quot;#div_load&quot;).hide(); // hiding loading
return;
};
// getting and converting duration in minutes
var durationInMin = parseInt(result[index2].duration.value / 60, 10);
counter++;
if ((durationInMin &gt; (slaTimeInMin * coverageMultiplier)) || (counter == 4)) {
((index2 - 1) == -1) ? final_vanReachablePoints.push(vanReachablePoints2[index2]) : final_vanReachablePoints.push(vanReachablePoints2[index2 - 1]);
index2 = start * 4;
start++;
counter = 0;
}
}
//---------------------------------------------------------------
// Plotting van, paths and updating van object
var sourceVan = new google.maps.LatLng(newLatOfVan, newLongOfVan);
// Plotting VAN&#x27;s reachable points
$.each(POSITIONING_JSON, function (index, van) {
if (van.VanId == vanId) {
deletePolygon(vanId); // Deleting the dragged Polygon
polyCoordinates = []; // taking empty array to store polygon coordinates
van.VanDefaultLatitude = newLatOfVan; // setting new lat to the Global JSON
van.VanDefaultLongitude = newLongOfVan; // setting new long to the Global JSON
// Remove previous polygon basis on &quot;title&quot;
for (var i = 0; i &lt; POLYGONS.length; i++) {
if (POLYGONS[i].title == van.VanId) {
POLYGONS[i].setMap(null);
POLYGONS.splice(i, 1);
}
}
// Plotting VAN&#x27;s reachable points
$.each(van.VanPostionList, function (point_index, point) {
var vanReachablePointId = point.VanPositionCoverageVanId + &#x27;_&#x27; + point.VanPositionCoverageId;
// One by one deleting route associated to this Van
deleteRoute(vanReachablePointId);
// One by one deleting VanReachable Points
deleteMarker(vanReachablePointId);
// if no point is there then set lat long to null
if (typeof final_vanReachablePoints[point_index] === &#x27;undefined&#x27;) {
// updating the Lat-Long of dragged item
//point.VanPositionCoverageVanLatitude = null;
//point.VanPositionCoverageVanLongitude = null;
point.VanPositionCoverageVanLatitude = &#x27;&#x27;;
point.VanPositionCoverageVanLongitude = &#x27;&#x27;;
}
else {
// updating the Lat-Long of dragged item
point.VanPositionCoverageVanLatitude = final_vanReachablePoints[point_index].lat();
point.VanPositionCoverageVanLongitude = final_vanReachablePoints[point_index].lng();
var reachablePointId = point.VanPositionCoverageVanId + &#x27;_&#x27; + point.VanPositionCoverageId;
var vanPointInfoWindow = &#x27;&lt;div&gt;&#x27; + reachablePointId + &#x27;&lt;/div&gt;&#x27;;
putMarkerOnMap(map, vanPointInfoWindow, point.VanPositionCoverageVanLatitude, point.VanPositionCoverageVanLongitude, &#x27;&#x27;, reachablePointId, vanReachablePointImagePath, true, false, false)
// Storing Point Cordinaates to draw a polygon
var reachablePoint = new google.maps.LatLng(point.VanPositionCoverageVanLatitude, point.VanPositionCoverageVanLongitude);
polyCoordinates.push(reachablePoint);
// craeting Route Object and storing that globally.
var routeObj = new Object({ &#x27;routeId&#x27;: reachablePointId, &#x27;source&#x27;: sourceVan, &#x27;destination&#x27;: reachablePoint });
MOVED_VAN_ROUTES.push(routeObj);
}
});
// Draw polygon and storing them globally
var polygon = drawPolygon(polyCoordinates, van.VanId);
POLYGONS.push(polygon);
// Drawing path for moved Van.
drawPathManagerForMovedVan();
// Creating Updated POSITIONING_JSON
createUpdatedPOSITIONING_JSON(van);
return;
}
});
//-------------------------------------------------
}
});
//----------------------------------------------
}, 1000);
}
/**
* To plot van reachable point at new position and draw its path with distance check from the van
* @method dragEndHandlerForVanReachablePoint
* @param {Object} marker reachbale point marker object on map
* @for PositioningTool
*/
function dragEndHandlerForVanReachablePoint(marker) {
$(&#x27;#get_van_coverage&#x27;).hide(); // Hiding the get-van-coverage button
$(&#x27;#update_van_coverage&#x27;).show(); // Showing update-van-coverage button
$(&#x27;#reset_van_coverage&#x27;).show(); // Showing update-van-coverage button
var vanId = marker.id.split(&#x27;_&#x27;)[0]; // getting van id
var markerId = marker.id.split(&#x27;_&#x27;)[1]; // getting van&#x27;s reachbale point id
// iterating through global JSON and updating that according for the dragged point
$.each(POSITIONING_JSON, function (index, van) {
if (van.VanId == vanId) {
// Getting new Lat-Long of the dragged marker.
var newLatOfPoint = marker.position.lat();
var newLongOfPoint = marker.position.lng();
// Calculating Distance and time between two locations.
getDistanceAndTime(van.VanDefaultLatitude, van.VanDefaultLongitude, newLatOfPoint, newLongOfPoint);
// Getting response from Direction-Matrix and Position the marker, drawing path accordingly
setTimeout(function () {
// If Travel time to newly dragged position is more than SLA-Time,
// then show alert and Put back the marker in the last eligible position
if ((distanceTimeObj.durationInMin == &#x27;undefined&#x27;) || (distanceTimeObj.durationInMin &gt;= slaTimeInMin)) {
var alertMessage = POSITIONING_MSG[&#x27;sla_exceed_error&#x27;] + slaTimeInMin;
jAlert(alertMessage, &#x27;Message&#x27;);
// Repositioning the marker to the last eligible location
$.each(van.VanPostionList, function (index, point) {
if (point.VanPositionCoverageId == markerId) {
marker.setPosition(new google.maps.LatLng(point.VanPositionCoverageVanLatitude, point.VanPositionCoverageVanLongitude));
}
});
return;
}
else {
// Making empty the polygon Coordinates Array
polyCoordinates = [];
// Plotting VAN&#x27;s reachable points
$.each(van.VanPostionList, function (index, point) {
// Storing Point Coordinates to draw a polygon
if (point.VanPositionCoverageId == markerId) {
polyCoordinates.push(marker.position);
// updating the Lat-Long of dragged item
point.VanPositionCoverageVanLatitude = newLatOfPoint;
point.VanPositionCoverageVanLongitude = newLongOfPoint;
}
else {
polyCoordinates.push(new google.maps.LatLng(point.VanPositionCoverageVanLatitude, point.VanPositionCoverageVanLongitude));
}
});
// Remove previous polygon basis on &quot;title&quot;
for (var i = 0; i &lt; POLYGONS.length; i++) {
if (POLYGONS[i].title == van.VanId) {
POLYGONS[i].setMap(null);
POLYGONS.splice(i, 1);
}
}
// Draw polygon and storing them globally
var polygon = drawPolygon(polyCoordinates, van.VanId);
POLYGONS.push(polygon);
// Creating Updated POSITIONING_JSON
createUpdatedPOSITIONING_JSON(van);
// Draw new path
var sourcePoint = new google.maps.LatLng(van.VanDefaultLatitude, van.VanDefaultLongitude);;
var destinationPoint = new google.maps.LatLng(marker.position.lat(), marker.position.lng());;
// delete existing path between source and this point and drawing a new path
var routeId = marker.id;
deleteRoute(routeId);
drawPath(sourcePoint, destinationPoint, routeId)
return;
}
}, 800);
}
});
}
////======================== Event / Action Handlers on Map Section End ===========================
////================== Draw / Put Objects on Map Section Start ==============================
/**
* To draw path between two points and setting am routeId for the same.
* @method drawPath
* @param {Object} sourcePoint source lat-long
* @param {Object} destinationPoint destination lat-long
* @param {Object} routeId route-id
* @for PositioningTool
*/
function drawPath(sourcePoint, destinationPoint, routeId) {
// Storing directions in direction object
if (!directionObj[routeId]) {
directionObj[routeId] = [];
}
// setting the renderer opting
var rendererOptions = {
preserveViewport: true,
suppressMarkers: true,
polylineOptions: { strokeColor: &quot;#1b3f94&quot; }
};
directionsRenderer = new google.maps.DirectionsRenderer(rendererOptions); // creating direction renderer object
directionsRenderer.setMap(map); // setting this direction renderer on map
directionObj[routeId].push(directionsRenderer); // pusshing the route object in the global direction object
// creating path request
var request = {
origin: sourcePoint,
destination: destinationPoint,
travelMode: google.maps.TravelMode.DRIVING
};
// Route the directions and pass the response to a
// function to create markers for each step.
directionService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsRenderer.setDirections(response);
}
});
}
/**
* To manage drawing paths on map at a time interval
* @method drawPathManagerForMovedVan
* @for PositioningTool
*/
function drawPathManagerForMovedVan() {
$(&quot;#div_load&quot;).show(); // showing loading
var maxTime = 0; // initializing loader timer
// iterating through global route array.
$.each(MOVED_VAN_ROUTES, function (index, route) {
setTimeout(function () {
drawPath(route.source, route.destination, route.routeId); // drawing path
}, ((index + 1) * 600));
maxTime = (index + 1) * 600; // increasing loader time
});
setTimeout(function () {
$(&quot;#div_load&quot;).hide(); // hiding loading
}, (maxTime + 500));
}
/**
* To manage drawing paths on map at a time interval
* @method drawPathManager
* @for PositioningTool
*/
function drawPathManager() {
$(&quot;#div_load&quot;).show(); // showing loading
var maxTime = 0; // initializing loader timer
// iterating through global route array.
$.each(ROUTES, function (index, route) {
setTimeout(function () {
drawPath(route.source, route.destination, route.routeId); // drawing path
}, ((index + 1) * 600));
maxTime = (index + 1) * 600; // increasing loader time
});
setTimeout(function () {
$(&quot;#div_load&quot;).hide(); // hiding loading
// Fitting all the markers on map area present on screen
map.fitBounds(latlngbounds);
}, maxTime);
}
/**
* To put a marker on map with supplied information.
* @method putMarkerOnMap
* @param {Object} map map object
* @param {String} markerInfoWindowContent info-window html string
* @param {Object} markerLat marker&#x27;s lat
* @param {Object} markerLong marker&#x27;s long
* @param {Object} markerTitle marker&#x27;s title
* @param {Object} markerId marker&#x27;s id
* @param {Object} markerImage marker&#x27;s icon image
* @param {Object} isDraggable true if marker is draggable
* @param {Object} setMapCenter true if marker click will center the map
* @param {Object} openInfoWindow true if info window should open
* @for PositioningTool
*/
function putMarkerOnMap(map, markerInfoWindowContent, markerLat, markerLong, markerTitle, markerId, markerImage, isDraggable, setMapCenter, openInfoWindow) {
var markerLatlng = new google.maps.LatLng(markerLat, markerLong); // creating marker&#x27;s object
var infowindow = new google.maps.InfoWindow({ content: markerInfoWindowContent }); // setting info window conent
// craeting marker&#x27;s object with proper info
var marker = new google.maps.Marker({
position: markerLatlng,
map: map,
title: markerTitle,
icon: markerImage,
draggable: isDraggable,
id: markerId
});
// click handler for marker when marker is cicked
google.maps.event.addListener(marker, &#x27;click&#x27;, function () {
if (openInfoWindow) { infowindow.open(map, marker); } // setting info window should open
if (setMapCenter) { map.setCenter(markerLatlng); } // setting center on map when marker is clicked
});
// dragend handler for marker when marker is dragged
google.maps.event.addListener(marker, &#x27;dragend&#x27;, function () {
// If moved marker is VAN-Reachable-Point
if (marker.id.indexOf(&#x27;_&#x27;) &gt;= 0) {
// plotting polygon and path on drag of a marker
dragEndHandlerForVanReachablePoint(marker);
}
// If moved marker is Van itself
else {
// plotting polygon and path on drag of a marker
dragEndHandlerForVan(marker);
}
});
MARKERS.push(marker); // pushing marker into global marker array
return marker;
}
/**
* To draw polygon on map with some lat-long
* @method drawPolygon
* @param {Array} polyCoordinates array of lat-long objects
* @param {String} polygonTitle polygon title
* @for PositioningTool
*/
function drawPolygon(polyCoordinates, polygonTitle) {
// Construct the polygon.
var polygon = new google.maps.Polygon({
paths: polyCoordinates,
strokeColor: &#x27;#AAA8A5&#x27;,
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: &#x27;#AAA8A5&#x27;,
fillOpacity: 0.35,
title: polygonTitle
});
polygon.setMap(map); // setting the polygon on map
return polygon; // returing the creating polygon
}
////================== Draw / Put Objects on Map Section End ==============================
///============== Delete/Remove Objects From Map Section Start ==============================
/**
* To delete a route based on the id
* @method deleteRoute
* @param {String} routeId Id of route
* @for PositioningTool
*/
function deleteRoute(routeId) {
var route = directionObj[routeId];
if (typeof route !== &#x27;undefined&#x27;) {
for (var i = 0; i &lt; route.length; i++) {
route[i].setMap(null);
}
}
}
/**
* To delete all routes from the map
* @method deleteAllRoutes
* @for PositioningTool
*/
function deleteAllRoutes() {
$.each(MARKERS, function (index, marker) {
if (marker.id.indexOf(&#x27;_&#x27;) &gt;= 0) {
deleteRoute(marker.id);
}
});
directionObj = {};
}
/**
* To delete all markers from the map
* @method deleteMarkers
* @for PositioningTool
*/
function deleteMarkers() {
for (var i = 0; i &lt; MARKERS.length; i++) {
MARKERS[i].setMap(null);
}
// Making the MARKERS-Array empty.
MARKERS = [];
}
/**
* To delete all van reachbale points from the map
* @method bs_deleteAllVanReachablePoint
* @for PositioningTool
*/
function bs_deleteAllVanReachablePoint() {
for (var i = 0; i &lt; BS_VAN_REACHABLE_POINT.length; i++) {
BS_VAN_REACHABLE_POINT[i].setMap(null);
}
// Making the MARKERS-Array empty.
BS_VAN_REACHABLE_POINT = [];
}
/**
* To delete marker from the map based on the id
* @method deleteMarker
* @param {String} markerId id of marker
* @for PositioningTool
*/
function deleteMarker(markerId) {
for (var i = 0; i &lt; MARKERS.length; i++) {
if (MARKERS[i].id == markerId) {
MARKERS[i].setMap(null);
MARKERS.splice(i, 1);
}
}
}
/**
* To delete all polygons from the map
* @method deleteAllPolygons
* @for PositioningTool
*/
function deleteAllPolygons() {
for (var i = 0; i &lt; POLYGONS.length; i++) {
POLYGONS[i].setMap(null);
}
POLYGONS = [];
}
/**
* To delete polygon from the map based on the id
* @method deletePolygon
* @param {String} polygonId id of polygon
* @for PositioningTool
*/
function deletePolygon(polygonId) {
for (var i = 0; i &lt; POLYGONS.length; i++) {
if (POLYGONS[i].title == polygonId) {
POLYGONS[i].setMap(null);
POLYGONS.splice(i, 1);
}
}
}
/**
* To delete polygon from the map based on the id (Blind Spot)
* @method bs_deletePolygon
* @param {String} polygonId id of polygon
* @for PositioningTool
*/
function bs_deletePolygon(polygonId) {
for (var i = 0; i &lt; BS_POLYGONS.length; i++) {
if (BS_POLYGONS[i].title == polygonId) {
BS_POLYGONS[i].setMap(null);
BS_POLYGONS.splice(i, 1);
}
}
}
/**
* To delete all polygons from the map based on the id (Blind Spot)
* @method bs_deleteAllPolygons
* @for PositioningTool
*/
function bs_deleteAllPolygons() {
for (var i = 0; i &lt; BS_POLYGONS.length; i++) {
BS_POLYGONS[i].setMap(null);
}
BS_POLYGONS = [];
}
/**
* To delete a route based on the id (Blind Spot)
* @method bs_deleteRoute
* @param {String} routeId Id of route
* @for PositioningTool
*/
function bs_deleteRoute(routeId) {
var route = bs_directionObj[routeId];
if (typeof route !== &#x27;undefined&#x27;) {
for (var i = 0; i &lt; route.length; i++) {
route[i].setMap(null);
}
}
bs_directionObj[routeId] = [];
}
/**
* To delete all routes from the map based on the id (Blind Spot)
* @method bs_deleteAllRoutes
* @for PositioningTool
*/
function bs_deleteAllRoutes() {
$.each(BS_VAN_REACHABLE_POINT, function (index, marker) {
bs_deleteRoute(marker.id);
});
bs_directionObj = {};
}
///============== Delete/Remove Objects From Map Section End ==============================
////=======================================================================
////================= MAIN Thread Start ===================================
/**
* To get all the Vans, place them on map, draw polygons and draw paths.
* @method getAllVansOnGeoView
* @for PositioningTool
*/
function getAllVansOnGeoView() {
if (!StateValid()) { return; } // If state is not selected, then no action.
slaTimeInMin = $(&quot;#slaCombobox&quot;).data(&quot;kendoDropDownList&quot;).text(); // Getting curent SLA time and storing that globally
$(&quot;#div_load&quot;).show(); // Showing Loading
$(&#x27;#get_van_coverage&#x27;).show(); // Showing the get-van-coverage button
$(&#x27;#update_van_coverage&#x27;).hide(); // Hiding update-van-coverage button
$(&#x27;#reset_van_coverage&#x27;).hide(); // Hiding update-van-coverage button
deleteAllRoutes(); // Deleting all the routes plotted on the map
ROUTES = []; // Making Routes array empty.
MOVED_VAN_ROUTES = []; // Making Moved-Van-Routes array empty.
POSITIONING_JSON = []; // Making the positioning json empty.
UPDATED_POSITIONING_JSON = []; // Making the UPDATED-POSITIONING-JSON empty.
latlngbounds = new google.maps.LatLngBounds(); // Creating Lat-Long bounds instance to fit all the markers on the map
// Getting the params which needs to be passed to the API
SecurityToken = securityToken;
utcMinutes = parseInt(UtcMinutes, 10);
UserId = userId;
var state = $(&quot;#stateCombobox&quot;).data(&quot;kendoComboBox&quot;).text(),
//city = $(&quot;#cityCombobox&quot;).data(&quot;kendoComboBox&quot;).text(),
//dealerId = $(&quot;#dealerCombobox&quot;).val(),
slaId = $(&quot;#slaCombobox&quot;).val();
//setMapCenterToAddress(city + &#x27; &#x27; + state); // Set map cneter to selected address
setMapCenterToAddress(state); // Set map cneter to selected address
$.ajax({
type: &quot;POST&quot;,
url: WCFRESTURL.GetAllVansOnGeoView,
data: { Token: SecurityToken, UtcMinutes: utcMinutes, UserId: UserId, State: state, City: &#x27;&#x27;, DealerId: &#x27;&#x27;, SlaId: slaId },
dataType: &quot;json&quot;,
success: function (data) {
POSITIONING_JSON = data; // Storing the Van-Data globally.
deleteMarkers(); // Removing all the markers from the map
deleteAllPolygons(); // removing polygon from the map
var polyCoordinates = []; // to store the van reachable points to draw polygon
$.each(data, function (index, van) {
polyCoordinates = []; // making the polygon store empty
// Plotting Van
var vanInfoWindow = &#x27;&lt;div class=&quot;&quot;&gt;&lt;h2 class=&quot;EngName_heading&quot;&gt;&#x27; + van.ServiceEngineerName + &#x27;&lt;/h2&gt;&lt;table class=&quot;InfoWindowTbl&quot; width=&quot;100%&quot; cellpadding=&quot;0&quot; cellspacing=&quot;0&quot;&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td&gt;&lt;span&gt;Organization Name&lt;/span&gt;&lt;/td&gt;&lt;td&gt;&#x27; + van.OrganizationName + &#x27;&lt;/td&gt;&lt;td&gt;&lt;span&gt;EOS Team Member&lt;/span&gt;&lt;/td&gt;&lt;td&gt;&#x27; + van.ServiceEngineerName + &#x27;&lt;/td&gt;&lt;td&gt;&lt;span&gt;VAN Registration No.&lt;/span&gt;&lt;/td&gt;&lt;td&gt;&#x27; + van.VanRegistrationNo + &#x27;&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;&lt;span&gt;Dealer City&lt;/span&gt;&lt;/td&gt;&lt;td&gt;&#x27; + van.DealerCity + &#x27;&lt;/td&gt;&lt;td&gt;&lt;span&gt;Mobile No.&lt;/span&gt;&lt;/td&gt;&lt;td&gt;&#x27; + van.ServiceEngineerContactNo + &#x27;&lt;/td&gt;&lt;td&gt;&lt;span&gt;VAN Model&lt;/span&gt;&lt;/td&gt;&lt;td&gt;&#x27; + van.VanModelName + &#x27;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;/div&gt;&lt;/div&gt;&#x27;;
var vanMarker = putMarkerOnMap(map, vanInfoWindow, van.VanDefaultLatitude, van.VanDefaultLongitude, van.ServiceEngineerName, van.VanId, vanImagePath, true, true, true)
var sourceVan = new google.maps.LatLng(van.VanDefaultLatitude, van.VanDefaultLongitude); // ceating van lat-long object
latlngbounds.extend(sourceVan); // extending lat-long object
// Plotting VAN&#x27;s reachable points
$.each(van.VanPostionList, function (index, point) {
// If lattitude is non null and non-empty then plotting starts
if ((point.VanPositionCoverageVanLatitude != &#x27;&#x27;) &amp;&amp; (point.VanPositionCoverageVanLatitude !== null)) {
var reachablePointId = point.VanPositionCoverageVanId + &#x27;_&#x27; + point.VanPositionCoverageId;
var vanPointInfoWindow = &#x27;&lt;div&gt;&#x27; + reachablePointId + &#x27;&lt;/div&gt;&#x27;;
putMarkerOnMap(map, vanPointInfoWindow, point.VanPositionCoverageVanLatitude, point.VanPositionCoverageVanLongitude, &#x27;&#x27;, reachablePointId, vanReachablePointImagePath, true, false, false)
// Storing Point Cordinaates to draw a polygon
var reachablePoint = new google.maps.LatLng(point.VanPositionCoverageVanLatitude, point.VanPositionCoverageVanLongitude);
polyCoordinates.push(reachablePoint);
latlngbounds.extend(reachablePoint); // extending lat-long object
// craeting Route Object and storing that globally.
var routeObj = new Object({ &#x27;routeId&#x27;: reachablePointId, &#x27;source&#x27;: sourceVan, &#x27;destination&#x27;: reachablePoint });
ROUTES.push(routeObj);
}
});
// Draw polygon and storing them globally
var polygon = drawPolygon(polyCoordinates, van.VanId);
POLYGONS.push(polygon);
});
},
complete: function () {
// Drawing path by sending route request effectively to Direction Service
drawPathManager();
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
}
////================= MAIN Thread End ===================================
////=====================================================================
//===============================================================================
//=========================== BLIND SPOT Start ===================================
/**
* To put a marker on map with supplied information. (Blind Spot)
* @method bs_putMarkerOnMap
* @param {Object} map map object
* @param {String} markerInfoWindowContent info-window html string
* @param {Object} markerLat marker&#x27;s lat
* @param {Object} markerLong marker&#x27;s long
* @param {Object} markerTitle marker&#x27;s title
* @param {Object} markerId marker&#x27;s id
* @param {Object} markerImage marker&#x27;s icon image
* @param {Object} isDraggable true if marker is draggable
* @param {Object} setMapCenter true if marker click will center the map
* @param {Object} openInfoWindow true if info window should open
* @for PositioningTool
*/
function bs_putMarkerOnMap(map, markerInfoWindowContent, markerLat, markerLong, markerTitle, markerId, markerImage, isDraggable, setMapCenter, openInfoWindow) {
var markerLatlng = new google.maps.LatLng(markerLat, markerLong); // creating lat-long object
var infowindow = new google.maps.InfoWindow({ content: markerInfoWindowContent }); // creating info-window object
// creating marker object
var marker = new google.maps.Marker({
position: markerLatlng,
map: map,
title: markerTitle,
icon: markerImage,
draggable: isDraggable,
id: markerId
});
// drag handler of marker
google.maps.event.addListener(marker, &#x27;dragend&#x27;, function () {
// if moved marker is van-reachable-point
if (marker.id.indexOf(&#x27;_&#x27;) &gt;= 0) {
// plotting polygon and path on drag of a marker
//dragendhandlerforvanreachablepoint(marker);
}
// if moved marker is van itself
else {
bs_deletePolygon(marker.id); // Deleting the dragged Polygon
BS_MOVED_VAN_ROUTES = []; // Making the Moved-Van-Routes array empty.
for (var index = 0; index &lt; 12 ; index++) {
var reachablePointId = vanId + &#x27;_&#x27; + index;
// One by one deleting route associated to this Van
bs_deleteRoute(reachablePointId);
// One by one deleting VanReachable Points
bs_deleteMarker(reachablePointId);
}
// plotting polygon and path on drag of a marker
bs_generateVanCoverage(marker);
}
});
return marker;
}
////============= Enable/Disable Tools ===================
/**
* To enable waypoint tool in blind spot toolbox
* @method enable_bs_waypoint_tool
* @for PositioningTool
*/
function enable_bs_waypoint_tool() {
disable_map_click_Listener = false; // enabling the map click
disable_map_click_Listener_waypoint = false; // enabling map click of waypoint tool
disable_map_mousemove_Listener_waypoint = false; // enabling mouse move of waypoint tool on map
$(&#x27;#bs_waypoint&#x27;).addClass(&#x27;selected_tool&#x27;); // select the waypoint tool
$(&#x27;#bs_van&#x27;).removeClass(&#x27;selected_tool&#x27;); // deselect van tool
disable_bs_van_tool(); // disabling the van tool
}
/**
* To disble waypoint tool in blind spot toolbox
* @method disable_bs_waypoint_tool
* @for PositioningTool
*/
function disable_bs_waypoint_tool() {
disable_map_click_Listener_waypoint = true; // disabling map click of waypoint tool
disable_map_mousemove_Listener_waypoint = true; // disabling mouse move of waypoint tool on map
}
/**
* To enable van tool in blind spot toolbox
* @method enable_bs_van_tool
* @for PositioningTool
*/
function enable_bs_van_tool() {
disable_map_click_Listener = false; // enabling map click
disable_map_mousemove_Listener_van = false; // enabling van tool when mouse is moved on map
disable_map_click_Listener_van = false; // enabling van-tool click on map
$(&#x27;#bs_van&#x27;).addClass(&#x27;selected_tool&#x27;); // select the van tool
$(&#x27;#bs_waypoint&#x27;).removeClass(&#x27;selected_tool&#x27;); // deselect the wayoint tool
deleteAllCircles(); // Deleting all the circles on map.
disable_bs_waypoint_tool(); // disable the waypoint tool
}
/**
* To disble van tool in blind spot toolbox
* @method disable_bs_van_tool
* @for PositioningTool
*/
function disable_bs_van_tool() {
disable_map_click_Listener_van = true; // disabling map click of van tool
disable_map_mousemove_Listener_van = true; // disabling mouse move of van tool on map
}
//==========================================================
/**
* To draw path between two points and setting am routeId for the same. (Blind Spot)
* @method bs_drawPath
* @param {Object} sourcePoint source lat-long
* @param {Object} destinationPoint destination lat-long
* @param {Object} routeId route-id
* @for PositioningTool
*/
function bs_drawPath(sourcePoint, destinationPoint, routeId) {
if (!bs_directionObj[routeId]) { bs_directionObj[routeId] = []; } // Storing directions
// creting renderer options to draw path on map
var rendererOptions = {
preserveViewport: true,
suppressMarkers: true,
polylineOptions: { strokeColor: &quot;#1b3f94&quot; }
};
directionsRenderer = new google.maps.DirectionsRenderer(rendererOptions); // creating renderer object
directionsRenderer.setMap(map); // setting it on map
bs_directionObj[routeId].push(directionsRenderer); // storing direction globally
// craeting path request between two points
var request = {
origin: sourcePoint,
destination: destinationPoint,
travelMode: google.maps.TravelMode.DRIVING
};
// Route the directions and pass the response to a
// function to create markers for each step.
directionService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsRenderer.setDirections(response);
}
});
}
/**
* To manage drawing paths on map at a time interval (Blind Spot)
* @method bs_drawPathManagerForMovedVan
* @for PositioningTool
*/
function bs_drawPathManagerForMovedVan() {
$(&quot;#div_load&quot;).show(); // showing loading
var maxTime = 0; // intializing maximum time
// iterating through global route array.
$.each(BS_VAN_ROUTES, function (index, route) {
setTimeout(function () { bs_drawPath(route.source, route.destination, route.routeId); }, ((index + 1) * 600)); // drawing path at an interval
maxTime = (index + 1) * 600; // inceasing loading time
});
setTimeout(function () {
$(&quot;#div_load&quot;).hide(); // hiding loading
// Fitting all the markers on map area present on screen
//map.fitBounds(latlngbounds);
}, (maxTime + 500));
}
/**
* To plot van at new position and draw its coverage and paths when there is No response from Google.
* @method bs_generateVanCoverageStatic
* @param {Object} marker van marker object on map
* @for PositioningTool
*/
function bs_generateVanCoverageStatic(marker) {
//$(&quot;#div_load&quot;).show(); // showing loading
var vanId = marker.id; // getting van id
//bs_enableCoverageDesign = true; // Enabling Coverage design
///bs_popTheVanOut = true; // enabling deleting the last van
//BS_VAN_ROUTES = []; // Making the Moved-Van-Routes array empty.
var newLatOfVan = marker.position.lat(); // getting new lat of marker
var newLongOfVan = marker.position.lng(); // getting new long of marker
// Getting Van reachable points at a given radius
var final_vanReachablePoints = bs_getCoverageForVanStatic(newLatOfVan, newLongOfVan, slaTimeInMin);
bs_coverageDesiged = true; // Coverage is designed once here
//================== Design Coverage =====================
var sourceVan = new google.maps.LatLng(newLatOfVan, newLongOfVan); // craeting source van lat-long object
var bs_polyCoordinates = []; // takign polygon lat-long array
// Plotting VAN&#x27;s reachable points
$.each(final_vanReachablePoints, function (index, point) {
//if ((typeof point === &#x27;undefined&#x27;) || (bs_enableCoverageDesign == false)) {
// if (bs_popTheVanOut &amp;&amp; BS_VAN_MARKERS.length &gt; 0) {
// var currentVanMarker = BS_VAN_MARKERS[BS_VAN_MARKERS.length - 1]; // getting last van marker
// BS_VAN_MARKERS.pop(); // poping out last van from global array
// currentVanMarker.setMap(null); // removing that from map
// bs_popTheVanOut = false; // disabling poping the van out further
// }
// jAlert(POSITIONING_MSG[&#x27;bs_put_van_error&#x27;], &#x27;Message&#x27;);
// $(&quot;#div_load&quot;).hide(); // hiding the loading
// return;
//};
var reachablePointId = vanId + &#x27;_&#x27; + index;
var bs_point = bs_putMarkerOnMap(map, &quot;&quot;, point.lat(), point.lng(), &quot;&quot;, reachablePointId, vanReachablePointImagePath, false, false, false);
BS_VAN_REACHABLE_POINT.push(bs_point);
// Storing Point Cordinaates to draw a polygon
var reachablePoint = new google.maps.LatLng(point.lat(), point.lng());
bs_polyCoordinates.push(reachablePoint);
// craeting Route Object and storing that globally.
var routeObj = new Object({ &#x27;routeId&#x27;: reachablePointId, &#x27;source&#x27;: sourceVan, &#x27;destination&#x27;: reachablePoint });
BS_ROUTES.push(routeObj);
BS_VAN_ROUTES.push(routeObj);
});
// Draw polygon and storing them globally
var polygon = drawPolygon(bs_polyCoordinates, vanId);
BS_POLYGONS.push(polygon);
// Drawing path for moved Van.
bs_drawPathManagerForMovedVan();
return;
//================== Design Coverage =====================
}
/**
* To generate van coverage for a marker
* @method bs_generateVanCoverage
* @param {Object} marker marker object
* @for PositioningTool
*/
function bs_generateVanCoverage(marker) {
$(&quot;#div_load&quot;).show(); // showing loading
var vanId = marker.id; // getting van id
bs_enableCoverageDesign = true; // Enabling Coverage design
bs_coverageDesiged = false; // No Coverage for now
bs_popTheVanOut = true; // enabling deleting the last van
BS_VAN_ROUTES = []; // Making the Moved-Van-Routes array empty.
var newLatOfVan = marker.position.lat(); // getting new lat of marker
var newLongOfVan = marker.position.lng(); // getting new long of marker
// Getting Van reachable points at a given radius
var vanReachablePoints = bs_getCoverageForVan(newLatOfVan, newLongOfVan, slaTimeInMin);
var vanReachablePoints1 = [];
var vanReachablePoints2 = [];
var mid = parseInt(vanReachablePoints.length / 2);
for (var i = 0; i &lt; mid ; i++) {
vanReachablePoints1.push(vanReachablePoints[i])
vanReachablePoints2.push(vanReachablePoints[mid + i]);
}
//----------------------
var final_vanReachablePoints = [];
//================== Design Coverage =====================
// Getting optimal reachable points for first 0 to 180 degrees
setTimeout(function () {
var request1 = {
origins: [marker.position],
destinations: vanReachablePoints1,
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}
distanceMatrixService.getDistanceMatrix(request1, function (response, status) {
if (status == google.maps.DistanceMatrixStatus.OK) {
var result = response.rows[0].elements;
var start = 1;
var counter = 0;
// getting optimal points for 0 to 180 degrees
for (var index = 0; index &lt; result.length; index++) {
if ((bs_coverageDesiged == false) &amp;&amp; (typeof result[index].duration === &#x27;undefined&#x27;)) {
//if (BS_VAN_MARKERS.length &gt; 0) {
// var currentVanMarker = BS_VAN_MARKERS[BS_VAN_MARKERS.length - 1]; // getting last van marker
// BS_VAN_MARKERS.pop(); // poping out last van from global array
// currentVanMarker.setMap(null); // removing that from map
// bs_popTheVanOut = false; // disabling poping the van out further
//}
//jAlert(POSITIONING_MSG[&#x27;bs_put_van_error&#x27;], &#x27;Message&#x27;);
bs_generateVanCoverageStatic(marker);
bs_enableCoverageDesign = false; // disabling coverage design
bs_coverageDesiged = true;
//$(&quot;#div_load&quot;).hide(); // hiding loading
return;
};
var durationInMin = parseInt(result[index].duration.value / 60, 10); // getting duration in minutes
counter++;
// getting optimal points for current SLA time
if ((durationInMin &gt; (slaTimeInMin * bs_coverageMultiplier)) || (counter == 4)) {
((index - 1) == -1) ? final_vanReachablePoints.push(vanReachablePoints1[index]) : final_vanReachablePoints.push(vanReachablePoints1[index - 1]);
index = start * 4;
start++;
counter = 0;
}
}
}
});
}, 300);
//--------------------------------
// Getting optimal reachable points for 180 to 360 degrees
setTimeout(function () {
//console.log(bs_coverageDesiged);
if (bs_coverageDesiged) { return; } // If coverage is designed once then exit the loop
var request2 = {
origins: [marker.position],
destinations: vanReachablePoints2,
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}
distanceMatrixService.getDistanceMatrix(request2, function (response, status) {
if (status == google.maps.DistanceMatrixStatus.OK) {
var result = response.rows[0].elements;
var start = 1;
var counter = 0;
// getting optimal points
for (var index = 0; index &lt; result.length; index++) {
if ((typeof result[index].duration === &#x27;undefined&#x27;) &amp;&amp; (bs_coverageDesiged == false)) {
//if (bs_popTheVanOut &amp;&amp; BS_VAN_MARKERS.length &gt; 0) {
// var currentVanMarker = BS_VAN_MARKERS[BS_VAN_MARKERS.length - 1]; // getting last van marker
// BS_VAN_MARKERS.pop(); // poping out last van from global array
// currentVanMarker.setMap(null); // removing that from map
// bs_popTheVanOut = false; // disabling poping the van out further
//}
//jAlert(POSITIONING_MSG[&#x27;bs_put_van_error&#x27;], &#x27;Message&#x27;);
bs_generateVanCoverageStatic(marker);
//$(&quot;#div_load&quot;).hide(); // hiding loading
return;
};
var durationInMin = parseInt(result[index].duration.value / 60, 10); // getting duration in minutes
counter++;
// getting optimal points for current SLA time
if ((durationInMin &gt; (slaTimeInMin * bs_coverageMultiplier)) || (counter == 4)) {
((index - 1) == -1) ? final_vanReachablePoints.push(vanReachablePoints2[index]) : final_vanReachablePoints.push(vanReachablePoints2[index - 1]);
index = start * 4;
start++;
counter = 0;
}
}
//--------------------Plotting van, its points and drawing paths and polygon------------------
var sourceVan = new google.maps.LatLng(newLatOfVan, newLongOfVan); // craeting source van lat-long object
var bs_polyCoordinates = []; // takign polygon lat-long array
// Plotting VAN&#x27;s reachable points
$.each(final_vanReachablePoints, function (index, point) {
if ((typeof point === &#x27;undefined&#x27;) || (bs_enableCoverageDesign == false)) {
//if (bs_popTheVanOut &amp;&amp; BS_VAN_MARKERS.length &gt; 0) {
// var currentVanMarker = BS_VAN_MARKERS[BS_VAN_MARKERS.length - 1]; // getting last van marker
// BS_VAN_MARKERS.pop(); // poping out last van from global array
// currentVanMarker.setMap(null); // removing that from map
// bs_popTheVanOut = false; // disabling poping the van out further
//}
//jAlert(POSITIONING_MSG[&#x27;bs_put_van_error&#x27;], &#x27;Message&#x27;);
//$(&quot;#div_load&quot;).hide(); // hiding the loading
return;
};
var reachablePointId = vanId + &#x27;_&#x27; + index;
var bs_point = bs_putMarkerOnMap(map, &quot;&quot;, point.lat(), point.lng(), &quot;&quot;, reachablePointId, vanReachablePointImagePath, false, false, false);
BS_VAN_REACHABLE_POINT.push(bs_point);
// Storing Point Cordinaates to draw a polygon
var reachablePoint = new google.maps.LatLng(point.lat(), point.lng());
bs_polyCoordinates.push(reachablePoint);
// craeting Route Object and storing that globally.
var routeObj = new Object({ &#x27;routeId&#x27;: reachablePointId, &#x27;source&#x27;: sourceVan, &#x27;destination&#x27;: reachablePoint });
BS_ROUTES.push(routeObj);
BS_VAN_ROUTES.push(routeObj);
});
// Draw polygon and storing them globally
var polygon = drawPolygon(bs_polyCoordinates, vanId);
BS_POLYGONS.push(polygon);
// Drawing path for moved Van.
bs_drawPathManagerForMovedVan();
return;
//------------------------------------------------------------------------------
}
});
}, 1000);
//================== Design Coverage =====================
}
/**
* To Calculate the blind spots on a path strech
* @method BlindSpotCalculator
* @param {Array} BS_waypoints Source to Destination waypoints
* @param {Array} BS_waypoints_reverse Destination to Source waypoints
* @param {Int} slaTimeInMin SLA Time in minutes
* @for PositioningTool
*/
function BlindSpotCalculator(BS_waypoints, BS_waypoints_reverse, slaTimeInMin) {
var bs_waypoints = BS_waypoints; // storing S--&gt;D waypoints locally
if (bs_waypoints.length == 0) {
jAlert(POSITIONING_MSG[&#x27;bs_no_waypoints&#x27;], &#x27;Message&#x27;);
$(&quot;#div_load&quot;).hide();
return;
}
var bs_waypoints_reverse = BS_waypoints_reverse; // storing D--&gt;S waypoints locally
var request_from_last_point_origin = bs_waypoints_reverse[0]; // getting source point
var request_from_first_point_origin = bs_waypoints[0]; // getting destination point
bs_waypoints.shift(); // removing source points from waypoints
bs_waypoints_reverse.shift(); // removing destination point from waypoints
//================== S --&gt; D =====================
// Getting BlindSpots while traversing from source to destinations
var request_from_first_point = {
origins: [request_from_first_point_origin],
destinations: bs_waypoints,
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}
distanceMatrixService.getDistanceMatrix(request_from_first_point, function (response, status) {
if (status == google.maps.DistanceMatrixStatus.OK) {
var sd_result = response.rows[0].elements;
var sd_startLatency = 0;
var sd_active_slaTime = slaTimeInMin;
var sd_setActiveSlaTime = false;
// if duration id undefined then reset the blind spots and reset it
if (typeof sd_result[sd_result.length - 1].duration === &#x27;undefined&#x27;) {
jAlert(POSITIONING_MSG[&#x27;bs_calculate_blind_spot_error&#x27;], &#x27;Message&#x27;);
resetBlindSpotGenerator(); // reset the blind spot geneartor
$(&quot;#div_load&quot;).hide(); // hiding loading
return;
};
// if duration is less tha SLA time then reset the blind spots and reset it
if (parseInt(sd_result[sd_result.length - 1].duration.value / 60, 10) &lt; slaTimeInMin) {
jAlert(POSITIONING_MSG[&#x27;bs_calculate_blind_spot_success&#x27;], &#x27;Message&#x27;);
$(&quot;#div_load&quot;).hide(); // hiding loading
enableBlindSpotGenerator = false; // disabling blind spot generator
return;
}
// getting Blind spots while traversing form source to destination
for (var sd_index = 0; sd_index &lt; sd_result.length; sd_index++) {
// if duration id undefined the reset the blind spot generator
if (typeof sd_result[sd_index].duration === &#x27;undefined&#x27;) {
jAlert(POSITIONING_MSG[&#x27;bs_calculate_blind_spot_error&#x27;], &#x27;Message&#x27;);
resetBlindSpotGenerator(); // reset the blind spot generator
$(&quot;#div_load&quot;).hide(); // hiding the loading
return;
};
// getting blind spots
if ((parseInt(sd_result[sd_index].duration.value / 60, 10) - sd_startLatency) &gt; sd_active_slaTime) {
// handling distributed placement of waypoints
if (sd_index == 0) {
jAlert(POSITIONING_MSG[&#x27;bs_calculate_blind_spot_warning&#x27;], &#x27;Message&#x27;);
resetBlindSpotGenerator(); //reset the blind spot
$(&quot;#div_load&quot;).hide(); // hiding loading
return;
}
BS_ENDS.push(bs_waypoints[sd_index - 1]); // storing the blind spots ends
sd_startLatency = parseInt(sd_result[sd_index - 1].duration.value / 60, 10); // resetting the start latency
// second time active sla time will be twice of the sla time
if (!sd_setActiveSlaTime) {
sd_active_slaTime = sd_active_slaTime * 2;
sd_setActiveSlaTime = true;
}
sd_index = sd_index - 1;
}
}
}
else {
jAlert(POSITIONING_MSG[&#x27;bs_calculate_blind_spot_error&#x27;], &#x27;Message&#x27;);
resetBlindSpotGenerator(); // reset the blind spot
$(&quot;#div_load&quot;).hide(); // hiding loading
return;
}
});
//================== S --&gt; D =====================
//================== D --&gt; S =====================
// Getting BlindSpots while traversing from destinations to source
setTimeout(function () {
var request_from_last_point = {
origins: [request_from_last_point_origin],
destinations: bs_waypoints_reverse,
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}
distanceMatrixService.getDistanceMatrix(request_from_last_point, function (response, status) {
if (status == google.maps.DistanceMatrixStatus.OK) {
var ds_result = response.rows[0].elements;
var ds_startLatency = 0;
var ds_active_slaTime = slaTimeInMin;
var ds_setActiveSlaTime = false;
// if duration id undefined then reset the blind spots and reset it
if (typeof ds_result[ds_result.length - 1].duration === &#x27;undefined&#x27;) {
jAlert(POSITIONING_MSG[&#x27;bs_calculate_blind_spot_error&#x27;], &#x27;Message&#x27;);
resetBlindSpotGenerator(); // reset the blind spot geneartor
$(&quot;#div_load&quot;).hide(); // hiding loading
return;
};
// if duration is less tha SLA time then reset the blind spots and reset it
if (parseInt(ds_result[ds_result.length - 1].duration.value / 60, 10) &lt; slaTimeInMin) {
jAlert(POSITIONING_MSG[&#x27;bs_calculate_blind_spot_success&#x27;], &#x27;Message&#x27;);
$(&quot;#div_load&quot;).hide(); // hiding loading
return;
}
// getting Blind spots while traversing form source to destination
for (var ds_index = 0; ds_index &lt; ds_result.length; ds_index++) {
// if duration id undefined then reset the blind spots and reset it
if (typeof ds_result[ds_index].duration === &#x27;undefined&#x27;) {
jAlert(POSITIONING_MSG[&#x27;bs_calculate_blind_spot_error&#x27;], &#x27;Message&#x27;);
resetBlindSpotGenerator(); // reset the blind spot geneartor
$(&quot;#div_load&quot;).hide(); // hiding loading
return;
};
// getting blind spots
if ((parseInt(ds_result[ds_index].duration.value / 60, 10) - ds_startLatency) &gt; ds_active_slaTime) {
if (ds_index == 0) {
jAlert(POSITIONING_MSG[&#x27;bs_calculate_blind_spot_warning&#x27;], &#x27;Message&#x27;);
resetBlindSpotGenerator(); // reset the blind spot geneartor
$(&quot;#div_load&quot;).hide(); // hiding loading
return;
}
BS_STARTS.unshift(bs_waypoints_reverse[ds_index - 1]); // storing the blind spots starts
ds_startLatency = parseInt(ds_result[ds_index - 1].duration.value / 60, 10); // resetting the start latency
// second time active sla time will be twice of the sla time
if (!ds_setActiveSlaTime) {
ds_active_slaTime = ds_active_slaTime * 2;
ds_setActiveSlaTime = true;
}
ds_index = ds_index - 1;
}
}
//------------ Draw blindspot range now ---------------
if (BS_ENDS.length == BS_STARTS.length) {
drawBlindSpotRegion(BS_STARTS, BS_ENDS);
}
else {
jAlert(POSITIONING_MSG[&#x27;bs_calculate_blind_spot_warning&#x27;], &#x27;Message&#x27;);
resetBlindSpotGenerator();
$(&quot;#div_load&quot;).hide();
return;
}
//----------------------------------------------------
}
else {
jAlert(POSITIONING_MSG[&#x27;bs_calculate_blind_spot_error&#x27;], &#x27;Message&#x27;);
resetBlindSpotGenerator();
$(&quot;#div_load&quot;).hide();
return;
}
});
}, 1000);
//================== D --&gt; S =====================
}
/**
* To draw blind spots and their region
* @method drawBlindSpotRegion
* @param {Array} bs_starts blind spot start points
* @param {Array} bs_ends blind spot end points
* @for PositioningTool
*/
function drawBlindSpotRegion(bs_starts, bs_ends) {
for (var index = 0; index &lt; bs_starts.length; index++) {
var points = []; // Making points arrray.
// pushing a set of positions to draw blind spots
points.push(bs_starts[index]);
points.push(bs_ends[index]);
// Getting distance between two points
var distance = google.maps.geometry.spherical.computeDistanceBetween(bs_starts[index], bs_ends[index]);
var radius = parseInt(distance / 2, 10);
var midpoint = getMidpoint(points, distance / 2); // Getting midpoint of two points.
var circle = drawCircle(midpoint, radius, (&#x27;circle_&#x27; + index)); // Drawing BlindSpot region
BS_CIRCLES.push(circle); // stroing blind spot circle globally
// putting bouncing down arrow on the middle of blind spots
var midMarker = new google.maps.Marker({
map: map,
draggable: false,
animation: google.maps.Animation.DROP,
position: midpoint,
icon: bs_downArrowImagePath,
id: &quot;arrow_&quot; + index
});
midMarker.setAnimation(google.maps.Animation.BOUNCE);
BS_ARROW_MARKERS.push(midMarker);
}
$(&quot;#div_load&quot;).hide();
}
/**
* To generate blind spots
* @method BlindSpotGenerator
* @for PositioningTool
*/
function BlindSpotGenerator() {
if (enableBlindSpotGenerator) {
$(&quot;#div_load&quot;).show();
BlindSpotCalculator(BS_WAYPOINTS, BS_WAYPOINTS_reverse, slaTimeInMin);
enableBlindSpotGenerator = false;
} else {
jAlert(POSITIONING_MSG[&#x27;bs_reset_tools&#x27;], &#x27;Message&#x27;);
$(&quot;#div_load&quot;).hide();
return;
}
}
/**
* To reset blind spots generator
* @method resetBlindSpotGenerator
* @for PositioningTool
*/
function resetBlindSpotGenerator() {
deleteWaypoints(); // Deleting waypoints markers from the map.
deleteVanMarkers(); // Deleting Van-Markers from the map.
deleteArrowMarkers(); // Deleting Arrow-Markers from the map.
deleteAllCircles(); // Deleting all the blind spot circles on map.
bs_deleteAllRoutes(); // Deleting all the routes from the map
bs_deleteAllPolygons(); // Deleting all the polygons
bs_deleteAllVanReachablePoint(); // Deleting all van reachbale points
$(&#x27;#bs_van&#x27;).removeClass(&#x27;selected_tool&#x27;); // deselect the van tool
$(&#x27;#bs_waypoint&#x27;).removeClass(&#x27;selected_tool&#x27;); // deselect the waypoint tool
// Re-Initializing all the global variables for BlindSpot.
BS_WAYPOINDID = 0;
BS_VAN_ID = 0;
disable_map_click_Listener = true;
disable_map_mousemove_Listener_waypoint = true;
disable_map_click_Listener_waypoint = true;
disable_map_click_Listener_van = true;
disable_map_mousemove_Listener_van = true;
enableBlindSpotGenerator = true;
bs_enableCoverageDesign = true;
bs_popTheVanOut = true;
bs_coverageDesiged = false;
BS_MARKERS = [];
BS_WAYPOINTS = [];
BS_WAYPOINTS_reverse = [];
BS_ENDS = [];
BS_STARTS = [];
BS_CIRCLES = [];
BS_MID_MARKERS = [];
BS_ARROW_MARKERS = [];
BS_VAN_REACHABLE_POINT = [];
BS_ROUTES = [];
}
/**
* To delete all the waypoints from the map
* @method deleteWaypoints
* @for PositioningTool
*/
function deleteWaypoints() {
for (var i = 0; i &lt; BS_MARKERS.length; i++) {
BS_MARKERS[i].setMap(null);
}
BS_MARKERS = []; // Making the Global waypoint-Array empty.
}
/**
* To delete all the van markers from the map
* @method deleteVanMarkers
* @for PositioningTool
*/
function deleteVanMarkers() {
for (var i = 0; i &lt; BS_VAN_MARKERS.length; i++) {
BS_VAN_MARKERS[i].setMap(null);
}
BS_VAN_MARKERS = []; // Making the Global Van-Array empty.
}
/**
* To delete all the arrow markers from the map
* @method deleteArrowMarkers
* @for PositioningTool
*/
function deleteArrowMarkers() {
for (var i = 0; i &lt; BS_ARROW_MARKERS.length; i++) {
BS_ARROW_MARKERS[i].setMap(null);
}
BS_ARROW_MARKERS = []; // Making the Global arrow-Array empty.
}
/**
* To delete all the circles from the map
* @method deleteAllCircles
* @for PositioningTool
*/
function deleteAllCircles() {
for (var i = 0; i &lt; BS_CIRCLES.length; i++) {
BS_CIRCLES[i].setMap(null);
}
BS_CIRCLES = []; // Making the global circle-Array empty.
}
//=========================== BLIND SPOT End ===================================
//==============================================================================
//===============================================================================
//===================== Google Map Initialization ===============================
/**
* To initialize the map and binding the event handlers
* @method initialize
* @for PositioningTool
*/
function initialize() {
var myLatlng = new google.maps.LatLng(defaultLat, defaultLng);
var mapOptions = {
zoom: 7,
center: myLatlng
};
map = new google.maps.Map(document.getElementById(&#x27;map-canvas&#x27;), mapOptions);
//===========================Geo Analysis report =========================
GA_openTicketMarkerArray = [];
GA_closeTicketMarkerArray = [];
GA_slaMeetMarkerArray = [];
GA_slaNotMeetMarkerArray = [];
// Set Mass By passing the Div Id
GA_SetMap(&#x27;map-canvas&#x27;);
/*Create a instance of OverlappingMarkerSpiderfier*/
oms = new OverlappingMarkerSpiderfier(map,
{ markersWontMove: true, markersWontHide: true });
//Put Marker On Map
GA_PutMarker(GA_ArrOpenTicket, GA_OpenTicketMarker, false);
GA_PutMarker(GA_ArrCloseTicket, GA_CloseTicketMarker, false);
var vTempMarkerCluster = GA_slaMeetMarkerArray.concat(GA_slaNotMeetMarkerArray);
masterClusterInstance = new MarkerClusterer(map, vTempMarkerCluster, { maxZoom: 9 });
//===========================Geo Analysis report End=========================
//Initialize the Direction Service
directionService = new google.maps.DirectionsService();
// Creating an instance of Google Distance Matrix
distanceMatrixService = new google.maps.DistanceMatrixService();
//================ Blind Spot Section =========================
google.maps.event.addListener(map, &#x27;click&#x27;, function (event) {
if (disable_map_click_Listener) {
return;
}
// if Waypoint is click on Map
if (!disable_map_click_Listener_waypoint) {
if (enableBlindSpotGenerator) {
if (BS_MARKERS.length &gt;= 25) {
jAlert(POSITIONING_MSG[&#x27;bs_waypoints_limit&#x27;], &#x27;Message&#x27;);
$(&quot;#div_load&quot;).hide();
return;
}
else {
var bs_waypointId = &#x27;bs_&#x27; + BS_WAYPOINDID;
var waypoint_marker = bs_putMarkerOnMap(map, &quot;&quot;, event.latLng.lat(), event.latLng.lng(), &#x27;&#x27;, bs_waypointId, bs_waypointImagePath, false, false, false);
BS_WAYPOINDID++;
BS_MARKERS.push(waypoint_marker);
BS_WAYPOINTS.push(event.latLng);
BS_WAYPOINTS_reverse.unshift(event.latLng);
}
}
else {
jAlert(POSITIONING_MSG[&#x27;bs_reset_tools&#x27;], &#x27;Message&#x27;);
$(&quot;#div_load&quot;).hide();
return;
}
}
// if VAN is click on Map
if (!disable_map_click_Listener_van) {
var bs_vanId = &#x27;bsVan&#x27; + BS_VAN_ID;
//pankaj working here: draw polygon and paths
var van_marker = bs_putMarkerOnMap(map, &quot;&quot;, event.latLng.lat(), event.latLng.lng(), &#x27;&#x27;, bs_vanId, bs_vanImagePath, false, false, false);
BS_VAN_MARKERS.push(van_marker);
BS_VAN_ID++;
bs_generateVanCoverage(van_marker);
}
});
google.maps.event.addListener(map, &#x27;mousemove&#x27;, function (event) {
if (disable_map_mousemove_Listener_waypoint &amp;&amp; disable_map_mousemove_Listener_van) {
map.setOptions({ draggableCursor: &#x27;&#x27; });
}
if (!disable_map_mousemove_Listener_waypoint) {
map.setOptions({ draggableCursor: &quot;url(&quot; + bs_waypointToolImagePath + &quot;), auto&quot; })
}
if (!disable_map_mousemove_Listener_van) {
map.setOptions({ draggableCursor: &quot;url(&quot; + bs_vanToolImagePath + &quot;), auto&quot; })
}
});
//============================================================
}
//===============================================================================
//===============================================================================
$(document).ready(function () {
$(&quot;#div_load&quot;).hide(); // hiding loading
$(&#x27;#get_van_coverage&#x27;).show() // Showing the get-van-coverage button
$(&#x27;#update_van_coverage&#x27;).hide(); // Hiding update-van-coverage button
$(&#x27;#reset_van_coverage&#x27;).hide(); // Hiding update-van-coverage button
loadAllSla(); // populating SLA combobox
loadStateChoices(); // populating state combobox
//loadCityChoices($(&quot;#stateCombobox&quot;).val()); // populating city combobox
//loadDealerChoices($(&quot;#stateCombobox&quot;).val(), $(&quot;#cityCombobox&quot;).val()); // populating dealer combobox
});
// Window is ready with all its resources, then load the Google-Map.
google.maps.event.addDomListener(window, &#x27;load&#x27;, initialize);
</pre>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="../assets/vendor/prettify/prettify-min.js"></script>
<script>prettyPrint();</script>
<script src="../assets/js/yui-prettify.js"></script>
<script src="../assets/../api.js"></script>
<script src="../assets/js/api-filter.js"></script>
<script src="../assets/js/api-list.js"></script>
<script src="../assets/js/api-search.js"></script>
<script src="../assets/js/apidocs.js"></script>
</body>
</html>