AnsweredAssumed Answered

How custom radius circle areas can be added as avoided areas?

Question asked by pcumino on Aug 9, 2016
Latest reply on Aug 11, 2016 by rscheitlin

I need to add circles as avoid areas centred in a specific position. Instead of a point, an area must be set as a barrier.

The function I'm using is addBarrier( ) as shown below:

function addBarrier() {
  var eventsArray = [];
  routeParams.barriers = new esri.tasks.FeatureSet();


  for (var i = 0; i < sensors.length; i++) {
  var aircondition = JSON.stringify(sensors[i].contextElement.attributes[0].value);
  aircondition = aircondition.toString(aircondition);
  aircondition = getNumber(aircondition);


  if(aircondition >= idealCondition){
  var position = JSON.stringify(sensors[i].contextElement.attributes[1].value);
  position = position.replace('"', '');
  position = position.replace('"', '');
  var posArray = position.split(',');
  var pnt = new esri.geometry.Point(posArray[1],posArray[0],new esri.SpatialReference(6864));


  routeParams.barriers.features.push(map.graphics.add(new esri.Graphic(esri.geometry.geographicToWebMercator(pnt), barrierSymbol)));
  }
  }
}

 

The addBarrier() function uses the location of the objects called sensor.

So instead of a simple symbol STYLE_CROSS to represent a barrier, a circle with a custom radius must be used.

The circles need to be centred the same way the barriers is being placed, using the parameter position of the sensor object.

The radius of each circle is defined inside each sensor.

 

This is the JSON representation of a sensor:

{
  "contextElement": {
    "type": "StreetFixed",
    "isPattern": "false",
    "id": "StreetFixed1",
    "attributes": [
      {
        "name": "aircondition",
        "type": "float",
        "value": "70"
      },
      {
        "name": "position",
        "type": "geo:point",
        "value": "-1.4521450790947026, -48.48221014022732"
      },
      {
        "name": "temperature",
        "type": "float",
        "value": "29"
      }
    ]
  },
  "statusCode": {
    "code": "200",
    "reasonPhrase": "OK"
  }
}

 

Here is the full code:

var sensors = getSensors();
var idealCondition = 0;


dojo.require("esri.map");
dojo.require("esri.urlUtils");
dojo.require("esri.geometry.Circle");
dojo.require("esri.tasks.route");
dojo.require("esri.toolbars.draw");
dojo.require("esri.arcgis.OAuthInfo");


var map;
var urlUtils;
var Circle, routeTask, routeParams, routes = [];
var drawToolbar;
var stopSymbol, barrierSymbol, polygonBarrierSymbol, routeSymbols;
var mapOnClick_addStops_connect;
var mapOnClick_addBarriers_connect;
var Point, SpatialReference;
var Polygon;


$(document).ready(function(){
  idealCondition = 0;


  $('input#airqualityslider').slider({
  formatter: function(value) {
  idealCondition = value;
  $("div#airqualityslider").html(value);
  return 'Air pollution filter: ' + value;
  }
  }).on('slideStop', function(evt){
  clearBarriers();
  addBarriers();
  if(routeParams.stops.features.length >= 2)
  solveRoute();
  });


  dojo.ready(init);


  $("#map").click(function(){
  addStops();
  });


  $("#clearStopsBtn").click(function(){
  clearStops();
  });


  $("#clearRoutesBtn").click(function(){
  clearRoutes();
  });


  $("#clearPolygons").click(function(){
  clearPolygonBarriers();
  });
});


function init() {
  map = new esri.Map("map", {
  basemap: "streets",
  // basemap: "topo-vector",
  center: [-48.47, -1.436],
  zoom: 13
  });


  function createToolBar() {
  drawToolbar = new esri.toolbars.Draw(map);
  drawToolbar.on("draw-end", addToMap);
  }


  function activateTool() {
  drawToolbar.activate(esri.toolbars.Draw.CIRCLE);
  }


  function addToMap(evt) {
  drawToolbar.markerSymbol.size = (Math.random() * (20 - 10) + 10);
  drawToolbar.deactivate();
  routeParams.polygonBarriers.features.push(
  map.graphics.add(new esri.Graphic(evt.geometry, polygonBarrierSymbol)));
  solveRoute();
  }
  map.on("load", createToolBar);
  var node = dojo.byId("addPolygons");
  dojo.connect(node, "click", activateTool);




  routeTask = new esri.tasks.RouteTask("https://route.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World");
  routeParams = new esri.tasks.RouteParameters();
  routeParams.stops = new esri.tasks.FeatureSet();
  routeParams.barriers = new esri.tasks.FeatureSet();
  routeParams.polygonBarriers = new esri.tasks.FeatureSet();
  routeParams.outSpatialReference = {"wkid":102100};




  dojo.connect(routeTask, "onSolveComplete", showRoute);
  dojo.connect(routeTask, "onError", errorHandler);


  stopSymbol = new esri.symbol.SimpleMarkerSymbol().setStyle(esri.symbol.SimpleMarkerSymbol.STYLE_CROSS).setSize(15);
  stopSymbol.outline.setWidth(5);


  barrierSymbol = new esri.symbol.SimpleMarkerSymbol().setStyle(esri.symbol.SimpleMarkerSymbol.STYLE_CROSS).setSize(15);
  barrierSymbol.outline.setWidth(3).setColor(new dojo.Color([255,0,0]));


  var polygonBarrierSymbol = new esri.symbol.SimpleFillSymbol();


  routeSymbols = {
  "Route 1": new esri.symbol.SimpleLineSymbol().setColor(new dojo.Color([0,0,255,0.5])).setWidth(5),
  "Route 2": new esri.symbol.SimpleLineSymbol().setColor(new dojo.Color([0,255,0,0.5])).setWidth(5),
  "Route 3": new esri.symbol.SimpleLineSymbol().setColor(new dojo.Color([255,0,255,0.5])).setWidth(5)
  };
}


function addStops() {
  removeEventHandlers();
  mapOnClick_addStops_connect = dojo.connect(map, "onClick", addStop);
}


function addStop(evt) {
// routeParams.stops.features.push(map.graphics.add(new esri.Graphic(evt.mapPoint,stopSymbol,{ RouteName:dojo.byId("routeName").value })));
routeParams.stops.features.push(map.graphics.add(new esri.Graphic(evt.mapPoint,stopSymbol,{ RouteName:"Route 1" })));
if(routeParams.stops.features.length >= 1)
  solveRoute();
addStops();
}


function clearStops() {
  removeEventHandlers();
  for (var i = routeParams.stops.features.length-1; i >= 0; i--) {
  map.graphics.remove(routeParams.stops.features.splice(i, 1)[0]);
  }
  clearRoutes();
  addStops();
}


function clearPolygonBarriers() {
  removeEventHandlers();
  for (var i=routeParams.polygonBarriers.features.length-1; i>=0; i--) {
  map.graphics.remove(routeParams.polygonBarriers.features.splice(i, 1)[0]);
  }
  solveRoute();
}


function addPolygonBarrier(evt) {
  drawToolbar.activate(esri.toolbars.Draw.CIRCLE);
  var drawEnd_connect = dojo.connect(drawToolbar, "onDrawEnd", function(geometry) {
  routeParams.polygonBarriers.features.push(
  map.graphics.add(new esri.Graphic(geometry, polygonBarrierSymbol))
  );
  });
}


function addBarriers(){
  removeEventHandlers();
  addBarrier();
}


function addBarrier() {
  var eventsArray = [];
  routeParams.barriers = new esri.tasks.FeatureSet();


  for (var i = 0; i < sensors.length; i++) {
  var aircondition = JSON.stringify(sensors[i].contextElement.attributes[0].value);
  aircondition = aircondition.toString(aircondition);
  aircondition = getNumber(aircondition);


  if(aircondition >= idealCondition){
  var position = JSON.stringify(sensors[i].contextElement.attributes[1].value);
  position = position.replace('"', '');
  position = position.replace('"', '');
  var posArray = position.split(',');
  var pnt = new esri.geometry.Point(posArray[1],posArray[0],new esri.SpatialReference(6864));


  routeParams.barriers.features.push(map.graphics.add(new esri.Graphic(esri.geometry.geographicToWebMercator(pnt), barrierSymbol)));
  }
  }
}


function clearBarriers() {
  removeEventHandlers();
  for (var i = routeParams.barriers.features.length - 1; i >= 0; i--) {
  map.graphics.remove(routeParams.barriers.features.splice(i, 1)[0]);
  }
  addStops();
}


function removeEventHandlers() {
  dojo.disconnect(mapOnClick_addStops_connect);
  dojo.disconnect(mapOnClick_addBarriers_connect);
}


function solveRoute() {
  clearBarriers();
  addBarriers();
  removeEventHandlers();
  if(routeParams.stops.features.length > 1){
  $("#map-loading").html("Solving route "+"<img src='/images/loading.gif'>");
  $("#map-loading").show();
  routeTask.solve(routeParams, function(){
  $("#map-loading").hide();
  });
  }
}


function clearRoutes() {
  for (var i=routes.length-1; i>=0; i--) {
  map.graphics.remove(routes.splice(i, 1)[0]);
  }
  routes = [];
  addStops();
}


function showRoute(solveResult) {
  clearRoutes();


  dojo.forEach(solveResult.routeResults, function(routeResult, i) {
  routes.push(
  map.graphics.add(
  routeResult.route.setSymbol(routeSymbols[routeResult.routeName])
  )
  );
  });


  var msgs = ["Server messages:"];
  dojo.forEach(solveResult.messages, function(message) {
  msgs.push(message.type + " : " + message.description);
  });
  if (msgs.length > 1) {
  alert(msgs.join("\n - "));
  }
}


function errorHandler(err) {
  // alert("An error occured\n" + err.message + "\n" + err.details.join("\n"));
  console.log(err);
}


function getSensors() {
  var result = "";
  var request = new XMLHttpRequest();


  if(localStorage.getItem('sensors') == null){
  // `false` makes the request synchronous
  request.open('GET', '../getSensors', false);
  request.send(null);


  if (request.status === 200) {
  result = JSON.parse(request.responseText).contextResponses;
  console.log("getSensors done! "+result.length+" sensors loaded.");
  localStorage.setItem("sensors", JSON.stringify(result));
  }
  else
  alert("Unknown error!");


  }
  else
  result = JSON.parse(localStorage.getItem('sensors'));


  return result;
}

 

Thanks in advance.

Outcomes