gis

js:读取配置文件

2018-05-29  本文已影响9人  gis杭州

前言 :gis开发中有很多地图url,直接写在各个js文件中,一旦需要修改(例如测试地址改为生产服务器上的arcgis服务地址)会非常麻烦。为了方便管理这些服务地址,让其他开发人员接手时也能明确项目中调用了哪些服务,引入配置文件显得很有必要。

下方代码是实际项目的一份js文件,里面带了3个gis相关的地址;一旦需要更改必须全局搜索然后逐个文件去修改地址,非常麻烦。(其他项目示例代码,与后文改造代码无关)

$(function () {
  initData();
});


function initData() {
  var touminigdu = 1;
  HXcommon.ajax('facilitymge/service/InfoDivide/GetInfo', {}, function (data) {
    var result = data.result;
    var html1 = '';
    var itemName = data.mainItem;
    var items = [];
    var no;
    for (var k = 0; k < itemName.length; k++) {
      if (itemName[k].mainBiz != '未划分') {
        items.push(itemName[k]);
      } else {
        no = itemName[k];
      }
    }
    items.push(no);
    itemName = items;

    for (var k = 0; k < itemName.length; k++) {
      var colorStr = itemName[k].color;
      var cs = colorStr.split(',');
      var color = [];
      for (var i = 0; i < cs.length; i++) {
        color.push(cs[i]);
      }

      html1 += '<div class="layui-col-xs2"><span class="default-btn " id="' + itemName[k].mainBiz + '" style="background-color:rgb(' + colorStr + ');">' + itemName[k].mainBiz + '</span></div>';
    }
    $("#biz").html(html1);
  });

}


require([
  "esri/map", "esri/layers/FeatureLayer", "esri/geometry/Extent",
  "esri/symbols/SimpleFillSymbol", "esri/symbols/SimpleLineSymbol",
  "esri/renderers/SimpleRenderer", "esri/SpatialReference", "esri/graphic",
  "esri/layers/GraphicsLayer", "esri/lang",
  "esri/geometry/Polygon","esri/Color", "dojo/number", "dojo/dom-style",
  "dijit/TooltipDialog", "dijit/popup", "dojo/domReady!"
], function (Map, FeatureLayer, Extent,
             SimpleFillSymbol, SimpleLineSymbol,
             SimpleRenderer,SpatialReference, Graphic, GraphicsLayer, esriLang,
             Polygon,Color, number, domStyle,
             TooltipDialog, dijitPopup) {
  var map, dialog;
  var myDynamicMapServiceLayer;
  var contentSql = "''";
  map = new Map("mapDiv", {
    slider: false,
    logo: false,
    minScale: 61984.128,
    maxScale: 968.5019999999997,
    extent: new Extent({xmin: -100, ymin: -4000, xmax: 8000, ymax: 100, spatialReference: 3857})
  });
  var mapUrl = "http://10.10.5.155:6080/arcgis/rest/services/wireless/wirelessMap/MapServer";
  var featureUrl = "http://10.10.5.155:6080/arcgis/rest/services/wireless/wirelessMap/FeatureServer/1";

  var mapBasicLayer = new esri.layers.ArcGISDynamicMapServiceLayer(mapUrl);
  map.addLayer(mapBasicLayer);

  myDynamicMapServiceLayer = new esri.layers.ArcGISDynamicMapServiceLayer(mapUrl);
  map.addLayer(myDynamicMapServiceLayer);

  var gLayerPolygon = new GraphicsLayer();
  map.addLayer(gLayerPolygon);
  var symbol = new SimpleFillSymbol();
  //填充色
  symbol.setColor(new Color([0, 0, 0, 0.25]));
  //边框颜色
  symbol.outline.setColor([255, 0, 0, 1]);
  symbol.outline.setWidth(3);

  var featureLayer = new esri.layers.FeatureLayer(featureUrl, {
    mode: esri.layers.FeatureLayer.MODE_ONDEMAND,
    outFields: ["*"]
  });
  var featureSymbol = new SimpleFillSymbol();//featureLayer加载空样式
  featureSymbol.setColor(new Color([255, 255, 255, 0])); //网格填充色设为空
  featureSymbol.outline.setColor([]);//边框颜色设为空
  featureLayer.setRenderer(new SimpleRenderer(featureSymbol));
  map.addLayer(featureLayer);//保持该图层在最上方 以便响应鼠标事件

  // map.infoWindow.resize(245,125);

  dialog = new TooltipDialog({
    id: "tooltipDialog",
    style: "position: absolute; width: 250px; font: normal normal normal 10pt Helvetica;z-index:100"
  });
  dialog.startup();

  map.on("load", function () {
    map.graphics.enableMouseEvents();
    map.graphics.on("mouse-out", closeDialog);
    map.graphics.on("click", hightlightGraphicClickHandler);
  });

  //移开鼠标 关闭信息框
  function closeDialog() {
    map.graphics.clear();
    dijitPopup.close(dialog);
  };

  //单击色块,弹出对应批文列表
  function hightlightGraphicClickHandler(evt) {
    console.log("频率信息是" + evt.graphic.attributes.CODE);
    var freqInfo = evt.graphic.attributes.CODE;
    HXcommon.layer.open('list.html?freqInfo=' + freqInfo, '批文列表', 'layer-fault-manage-txt', '1100', '570');
  }

  //色块鼠标移入添加高亮显示、信息框展示
  featureLayer.on("mouse-over", function (evt) {
    closeDialog();
    var t = "<b>${TYPE}</b><hr><b>频率范围: </b>${CODE}<br>"
      + "<b>详细信息: </b>${DETAIL}<br>";
    var highlightSymbol = new SimpleFillSymbol(//鼠标滑过高亮显示样式
      SimpleFillSymbol.STYLE_SOLID,
      new SimpleLineSymbol(
        SimpleLineSymbol.STYLE_SOLID,
        new Color([255, 0, 0]), 1.5
      ),
      new Color([125, 0, 0, 0.3])
    );
    var content = esriLang.substitute(evt.graphic.attributes, t);
    var highlightGraphic = new Graphic(evt.graphic.geometry, highlightSymbol);
    highlightGraphic.setAttributes(evt.graphic.attributes);
    map.graphics.add(highlightGraphic);

    dialog.setContent(content);

    domStyle.set(dialog.domNode, "opacity", 0.85);
    dijitPopup.open({
      popup: dialog,
      x: evt.pageX,
      y: evt.pageY
    });
  });


  //点击某一类别的无线电按钮,高亮显示该类别所有色块
  $("#biz").on('click', 'span', function (evt) {
    closeDialog();
    map.setExtent(new Extent({xmin: -100, ymin: -4000, xmax: 8000, ymax: 100, spatialReference: 3857}));
    var queryName = ",'" + evt.currentTarget.innerText + "'";
    if ($(this).hasClass("cur")) {
      contentSql = contentSql.split(queryName)[0] + contentSql.split(queryName)[1];
      $(this).removeClass("cur");
      $(this).css("border", "2px solid transparent");
    } else {
      contentSql += queryName;
      $(this).addClass("cur");
      $(this).css("border", "green 1px solid");
    }

    var layerDefinitions = [];
    layerDefinitions[1] = "type in(" + contentSql + ")";
    myDynamicMapServiceLayer.setLayerDefinitions(layerDefinitions);

    if ("''" == contentSql) {//取消所有选中后恢复底图默认透明度
      mapBasicLayer.setOpacity(1);
    } else {
      mapBasicLayer.setOpacity(0.1);
    }
  });

  //点击定位按钮,频谱图定位到对应输入位置并标示范围(或单条竖线)
  $("#navigate").on('click', function (evt) {
    var startNumber,endNumber;
    var hzStr = $("#endunit").find("option:selected").text();
    var xyObj;
    if(""==$("#startfreq").val()){//无输入
      HXcommon.layer.alert("请输入频率值");
    }else if(""!=$("#startfreq").val()&&""==$("#endfreq").val()){//单一输入,线条展示
      startNumber = parseFloat($("#startfreq").val());
      if(isNaN(startNumber)){//不是数字,错误输入
        HXcommon.layer.alert("输入有误,请重新输入数值");
        return;
      }else{//正确输入了单一数值
        xyObj = getXYvalue(hzStr, startNumber, startNumber);
        creatGraphic(xyObj);
      }
    }else if(""!=$("#startfreq").val()&&""!=$("#endfreq").val()){//范围区域面展示
      startNumber = parseFloat($("#startfreq").val());
      endNumber = parseFloat($("#endfreq").val());
      if(isNaN(startNumber)||isNaN(endNumber)){//不是数字,错误输入
        HXcommon.layer.alert("输入有误,请重新输入数值");
        return;
      }else{//正确输入了两个数值
        xyObj = getXYvalue(hzStr, startNumber, endNumber);
        creatGraphic(xyObj);
      }
    }
  });




function getXYvalue(hzStr, startNumber, endNumber) {
  var xEnd = 0;
  var yValue = 0;
  var subtotal = 0;//每条频谱图代表频点范围数值
  var ownNumber;//所属第几行数据
  if (hzStr.toLowerCase() === "khz") {//1、2两行数据
    if (endNumber <= 300) {//第1行数据
      yValue = 20;
      ownNumber = 1;
      subtotal = 300;
    } else if (startNumber >= 300 && endNumber <= 3000) {//第2行数据
      yValue = -470;
      ownNumber = 2;
      subtotal = 3000 - 300;
    } else if (startNumber > 3000) {//eg:21000.000kHz~21450.000kHz,表达为21MHz~21.45MHz,归入第三行显示
      yValue = -980;
      ownNumber = 3;
      subtotal = 30 - 3;
      startNumber = startNumber / 1000;
      endNumber = endNumber / 1000;
    }
  } else if (hzStr.toLowerCase() === "mhz") {//3、4、5行数据
    if (startNumber >= 3 && endNumber <= 30) {//第3行数据
      yValue = -980;
      ownNumber = 3;
      subtotal = 30 - 3;
    } else if (startNumber >= 30 && endNumber <= 300) {//第4行数据
      yValue = -1495;
      ownNumber = 4;
      subtotal = 300 - 30;
    } else if (startNumber >= 300 && endNumber <= 3000) {//第5行数据
      yValue = -2008;
      ownNumber = 5;
      subtotal = 3000 - 300;
    } else if (startNumber > 3000) {//eg:5780.000MHz~5780.000MHz,表达为5.78GHz~5.78GHz,归入第6行显示
      yValue = -2520;
      ownNumber = 6;
      subtotal = 30 - 3;
      startNumber = startNumber / 1000;
      endNumber = endNumber / 1000;
    }
  } else if (hzStr.toLowerCase() === "ghz") {//6、7两行数据
    if (startNumber >= 3 && endNumber <= 30) {//第6行数据
      yValue = -2520;
      ownNumber = 6;
      subtotal = 30 - 3;
    } else if (startNumber >= 30 && endNumber <= 1000) {//第7行数据
      yValue = -3034;
      ownNumber = 7;
      subtotal = 280 - 30;
    }
  } else {//错误数据,传入数据格式不正确
    console.warn("错误数据,检查数据格式是否带单位");
  }
  var startObj = getXAndName(startNumber, ownNumber);

  var xStart = startObj.closestX + 7960 * (startNumber - startObj.closestName) / subtotal;
  if (startNumber === endNumber) {//一条线
    xEnd = xStart;
  } else {//矩形,需要查询构成矩形下一个点的x坐标
    var endObj = getXAndName(endNumber, ownNumber);
    xEnd = endObj.closestX + 7960 * (endNumber - endObj.closestName) / subtotal;
  }
  return {xStart: xStart, xEnd: xEnd, y: yValue};
}

//查询后台最近点坐标并返回该最近点对应的x坐标与频点信息(name字段)
function getXAndName(name, ownNumber) {
  var closestX = 0;//最近点x坐标
  var closestName = 0;//最近点频点值
  $.ajax({
    type: "GET",
    url: "http://10.10.5.155:8080/gisMap/wireless/getCoordinates/" + name + "/" + ownNumber,
    dataType: "json",
    async: false,
    success: function (obj) {
      console.log("--ok get it " + obj[0]);
      closestX = Number(obj[0].x);
      closestName = Number(obj[0].name);
    },
    error: function () {
      console.log("请求错误");
      closestX = "error";
      closestName = "error";
      HXcommon.layer.alert("输入范围跨度太大");
    }
  });
  return {
    closestX: closestX,
    closestName: closestName
  };
}

function creatGraphic(xyObj) {
  gLayerPolygon.clear();
  if(isNaN(xyObj.xStart)){//返回错误,不是数值的x
    map.setExtent(new Extent({xmin: -100, ymin: -4000, xmax: 8000, ymax: 100, spatialReference: 3857}));
    return;
  }
  mapBasicLayer.setOpacity(0.7);

  //绘制多边形
  var polygon = new Polygon(new SpatialReference({wkid: 3857}));
  var YMOVE = 540;
  var x1 = xyObj.xStart;
  var y1 = xyObj.y;
  var x2 = xyObj.xEnd;
  var y2 = y1;
  var x3 = xyObj.xEnd;
  var y3 = y1 - YMOVE;
  var x4 = x1;
  var y4 = y1 - YMOVE;
  polygon.addRing([[x1, y1], [x2, y2], [x3, y3], [x4, y4], [x1, y1]]);
  var graphic = new Graphic(polygon, symbol);
  gLayerPolygon.add(graphic);

  // map.setScale(Number(map.getScale()) / 4);
  map.centerAt(polygon.getExtent().getCenter());
};

  //清除
  $("#clerGraphic").on('click', function (evt) {
    gLayerPolygon.clear();
    map.setExtent(new Extent({xmin: -100, ymin: -4000, xmax: 8000, ymax: 100, spatialReference: 3857}));
  })
});


END 前言结束


1 新建一个gisConfig.json文件,写入相关的地址(此处只写了一个地址测试用),存放在config目录下。

image.png

2 新建mapLoader.js,在html页面业务代码js文件前引入;在此编写读取配置文件代码

image.png
var HXDIGIS = {};
HXDIGIS.MapLoader = function(opt_options) {

  this.gisConfig_ = null;
  this.loadConfig_();

};
$.extend(HXDIGIS.MapLoader.prototype, {
  loadConfig_: function() {
    var me = this;
    $.ajax({
      async: false,
      url: "configs/gisConfig.json",
      type: 'GET',
      dataType: 'json',
    }).done(function(data) {
      me.gisConfig_ = data;

    }).fail(function(data, status, desc) {
      alert("无法获取配置信息或配置信息有误!");
      throw new Error(status + "\n" + desc);
    });
  },

  getGISConfig: function() {
    return this.gisConfig_;
  }

});

3 修改原有的调用代码,改为从配置文件读取到的url地址

 var maploader = new HXDIGIS.MapLoader();
      var gisConfig = maploader.getGISConfig();
      var baseMapUrl = gisConfig["Map"]["baseMapUrl"];
      // var baseMapUrl = "http://10.10.1.122:6080/arcgis/rest/services/tile/gaodeTile/MapServer";
      var baseLayer = new ArcGISTiledMapServiceLayer(baseMapUrl);
      map.addLayer(baseLayer);

END 结束示例


上述写法引入了HXDIGIS这一全局变量,而且必须在html页面中引入读取配置文件的js文件。利用dojo的js模块化开发改进这一功能,具体步骤如下:
1新建模块,存放在myMoudles文件夹下


image.png

模块内代码如下 MapLoader.js

define([], function() {
    var MapLoader = function(opt_options) {
    this.gisConfig_ = null;
    this.loadConfig_();
  };
  $.extend(MapLoader.prototype, {
    loadConfig_: function() {
      var me = this;
      $.ajax({
        async: false,
        url: "configs/gisConfig.json",
        type: 'GET',
        dataType: 'json',
      }).done(function(data) {
        me.gisConfig_ = data;

      }).fail(function(data, status, desc) {
        alert("无法获取配置信息或配置信息有误!");
        throw new Error(status + "\n" + desc);
      });
    },
    getGISConfig: function() {
      return this.gisConfig_;
    }
  });

  return MapLoader;
  }
);

2 在主页面html文件中配置本地模块的路径,注意,这段配置代码需要写在引入arcgis js api的init.js文件之前

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>pointMap</title>
    <style>
        html, body, #mapdiv {
            height: 100%;
            width: 100%;
            margin: 0;
            padding: 0;
        }
    </style>
    <link rel="stylesheet" type="text/css"
          href="http://10.10.5.155:8080/arcgis_js_api_3.20/library/3.20/3.20/esri/css/esri.css"/>
    <link rel="stylesheet" href="css/bootstrap-3.3.5.css">
    <link rel="stylesheet" href="css/mapChange.css">

</head>
<body>
<div id="mapdiv" class="MapClass"></div>
</body>
<script>var dojoConfig = {
  parseOnLoad: true,
  packages: [{
    "name": "myModules",
    "location": location.pathname.replace(/\/[^/]+$/, "") + "/js/myModules"
  }]
};
</script>
<script src="js/coordtransform.js"></script>
<script type="text/javascript" src="http://10.10.5.155:8080/arcgis_js_api_3.20/library/3.20/3.20/init.js"></script>
<script src="js/jquery-2.1.3.js"></script>
<script src="js/bootstrap-3.3.5.js"></script>
<!--<script src="js/mapLoader.js"></script>-->
<script type="text/javascript" src="js/qingdaoPoint.js"></script>
<script src="js/mapChange.js"></script>
</html>

3 代码中调用


image.png
上一篇下一篇

猜你喜欢

热点阅读