Acrgis jsapi 地图基本属性 事件 工具 测距等

arcgis 官方测距 demo Measurement

<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

    <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">
    <title>Measure Tool</title>
    <link rel="stylesheet" href="https://js.arcgis.com/3.16/esri/themes/calcite/dijit/calcite.css">
    <link rel="stylesheet" href="https://js.arcgis.com/3.16/esri/themes/calcite/esri/esri.css">
    <style>
        html,
        body {
            height: 100%;
            width: 100%;
            margin: 0;
        }
        
        body {
            background-color: #FFF;
            overflow: hidden;
            font-family: "Trebuchet MS";
        }
        
        #map {
            border: solid 2px #808775;
            -moz-border-radius: 4px;
            -webkit-border-radius: 4px;
            border-radius: 4px;
            margin: 5px;
            padding: 0px;
        }
        
        #titlePane {
            width: 280px;
        }
    </style>
    <script src="https://js.arcgis.com/3.16/"></script>
    <script>
        var map;
        require([
            "dojo/dom",
            "esri/Color",
            "dojo/keys",
            "dojo/parser",

            "esri/config",
            "esri/sniff",
            "esri/map",
            "esri/units",
            "esri/SnappingManager",
            "esri/dijit/Measurement",
            "esri/layers/FeatureLayer",
            "esri/renderers/SimpleRenderer",
            "esri/tasks/GeometryService",
            "esri/symbols/SimpleLineSymbol",
            "esri/symbols/SimpleFillSymbol",

            "esri/dijit/Scalebar",
            "dijit/layout/BorderContainer",
            "dijit/layout/ContentPane",
            "dijit/TitlePane",
            "dijit/form/CheckBox",
            "dojo/domReady!"
        ], function(
            dom, Color, keys, parser,
            esriConfig, has, Map, Units, SnappingManager, Measurement, FeatureLayer, SimpleRenderer, GeometryService, SimpleLineSymbol, SimpleFillSymbol
        ) {
            parser.parse();
            //This sample may require a proxy page to handle communications with the ArcGIS Server services. You will need to
            //replace the url below with the location of a proxy on your machine. See the 'Using the proxy page' help topic
            //for details on setting up a proxy page.
            esriConfig.defaults.io.proxyUrl = "/proxy/";
            esriConfig.defaults.io.alwaysUseProxy = false;

            //This service is for development and testing purposes only. We recommend that you create your own geometry service for use within your applications
            esriConfig.defaults.geometryService = new GeometryService("https://tasks.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer");

            map = new Map("map", {
                basemap: "satellite",
                center: [-85.74338.256],
                zoom: 17
            });

            var sfs = new SimpleFillSymbol(
                "solid",
                new SimpleLineSymbol("solid"new Color([19517623]), 2),
                null
            );

            var parcelsLayer = new FeatureLayer("https://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Louisville/LOJIC_LandRecords_Louisville/MapServer/0", {
                mode: FeatureLayer.MODE_ONDEMAND,
                outFields: ["*"]
            });
            parcelsLayer.setRenderer(new SimpleRenderer(sfs));
            map.addLayers([parcelsLayer]);

            //dojo.keys.copyKey maps to CTRL on windows and Cmd on Mac., but has wrong code for Chrome on Mac
            var snapManager = map.enableSnapping({
                snapKey: has("mac"? keys.META : keys.CTRL
            });
            var layerInfos = [{
                layer: parcelsLayer
            }];
            snapManager.setLayerInfos(layerInfos);

            var segmentLength = 0//used in measure tool to track last segment length
            var measureLength = 0// total current length of the line
            var PrevM = 0//used in measure tool to track last total measurement
            var Mtype = ''//used to track measurement units for display
            var toolInUse = '';  // used to track which tool is being used

            var measurement = new Measurement({
                map: map,
                defaultAreaUnit: Units.ACRES,
                defaultLengthUnit: Units.FEET,
            }, dom.byId("measurementDiv"));
            measurement.startup();
            var measurementHandler;

            measurement.on("measure-start"function(evt) {
                measurementHandler = map.on('click', measureSegment);
                segmentLength = 0;
                PrevM = 0;
            });

            measurement.on("measure"function(evt) {
                measureLength = evt.values;
            });

            measurement.on("measure-end"function(evt) {
                measurementHandler.remove();
                PrevM = 0
            });

            measurement.on("tool-change"function(evt) {
                dom.byId('spanSegment').innerHTML = ''//zero out current values
                toolInUse = evt.toolName;
                Mtype = evt.unitName;
            });

            measurement.on("unit-change"function(evt) {
                Mtype = evt.unitName;
            });

            function measureSegment(e) {
                if (toolInUse === 'distance') {
                    segmentLength = measureLength - PrevM; //new segment value
                    dom.byId('spanSegment').innerHTML = 'Segment Length: ' + segmentLength.toFixed(1+ ' ' + Mtype;
                    PrevM = measureLength;
                }
            }

        });
    </script>
</head>

<body class="calcite">
    <div id="mainWindow" data-dojo-type="dijit/layout/BorderContainer" data-dojo-props="design:'headline',gutters:false" style="width:100%; height:100%;">
        <div id="map" data-dojo-type="dijit/layout/ContentPane" data-dojo-props="region:'center'">
            <div style="position:absolute; right:20px; top:10px; z-Index:999;">
                <div id="titlePane" data-dojo-type="dijit/TitlePane" data-dojo-props="title:'Measurement', closable:false, open:false">
                    <div id="measurementDiv"></div>
                    <span id="spanSegment"></span><br>
                    <span style="font-size:smaller;padding:5px 5px;">Press <b>CTRL</b> to enable snapping.</span>
                </div>
            </div>
        </div>
    </div>
</body>

</html>

ArcGIS API for JavaScript实现地图双屏联动

 
ArcGIS API for JavaScript实现地图双屏联动
2014-04-04 10:44 671人阅读 评论(0) 收藏 举报

 分类:
 
arcgis javascript版本地图开发 Dojo(2) 

版权声明:本文为博主原创文章,未经博主允许不得转载。
         使用ArcGIS API for JavaScript,可以很方便的实现地图联动。最简单的方式是借助Map对象的extent-change 事件,当然,也可以借助zoom-end、pan-end、mouse-drag-end等事件,本文使用第一种方式,实现地图的平移联动、鼠标双击放大联动、点击缩放按钮联动等,具体实现代码如下:
[html] view plain copy print?


<!-- 
功能:地图分屏 
-->  

<!-- 
功能:地图分屏 
-->  
<!DOCTYPE html>  
<html>  
<head>  
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">  
    <!--The viewport meta tag is used to improve the presentation and behavior of the samples  
      on iOS devices-->  
    <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">  
    <title>地图分屏</title>  
    <link rel="stylesheet" href="http://js.arcgis.com/3.8/js/dojo/dijit/themes/claro/claro.css">  
    <link rel="stylesheet" href="http://js.arcgis.com/3.8/js/esri/css/esri.css">  
    <link rel="stylesheet" href="css/fenping.css">  
    <script src="http://js.arcgis.com/3.8/"></script>  
    <script>  
        require([  
            "dojo/ready",  
            "dojo/parser",  
            "dijit/layout/BorderContainer",  
            "dijit/layout/ContentPane",  
            "esri/map",  
            "esri/geometry/Extent",  
            "esri/layers/ArcGISTiledMapServiceLayer",  
            "dojo/domReady!"  
        ], function(ready,parser,BorderContainer, ContentPane,Map,Extent,ArcGISTiledMapServiceLayer) {  
            parser.parse();  
            /*  
             * 矢量地图的构建  
             */  
            var vecMap=new Map("vecMap",{  
                extent: new Extent({xmin:105,ymin:31,xmax:110,ymax:40,  
                    spatialReference:{wkid:4326}}),  
                logo:false  
            });  
            var tiledMapServiceLayerV=new ArcGISTiledMapServiceLayer("矢量地图服务的url");  
            vecMap.addLayer(tiledMapServiceLayerV);  
            /*  
             * 影像地图的构建  
             */  
            var imgMap=new Map("imgMap",{  
                extent: new Extent({xmin:105,ymin:31,xmax:110,ymax:40,  
                    spatialReference:{wkid:4326}}),  
                logo:false  
            })  
            var tiledMapServiceLayerI=new ArcGISTiledMapServiceLayer("影像地图的url");  
            imgMap.addLayer(tiledMapServiceLayerI);  
            /*  
             * 添加extent-change事件,实现地图联动  
             * flagV矢量地图的extent-change控制标志,flagI影像地图的extent-change控制标志消除死循环情况  
             */  
            var flagV=true,flagI=true;  
            vecMap.on("extent-change",function(){  
                if(flagV){  
                    var vExtent=vecMap.extent;  
                    imgMap.setExtent(vExtent);  
                    flagI=false;  
                }else if(!flagV){  
                    flagV=true;  
                }  
            });  
            imgMap.on("extent-change",function(){  
                if(flagI){  
                    var iExtent=imgMap.extent;  
                    vecMap.setExtent(iExtent);  
                    flagV=false;  
                }else if(!flagI){  
                    flagI=true;  
                }  
            });  
  
        });  
    </script>  
</head>  
  
<body class="claro">  
<div id="mainWindow" data-dojo-type="dijit.layout.BorderContainer" data-dojo-props="design:'headline'"  
     style="width:100%; height:100%;">  
    <div id="header" data-dojo-type="dijit.layout.ContentPane" data-dojo-props="region:'top'">  
        <div id="title">天地图</div>  
        <div id="snippet">  
        </div>  
    </div>  
  
    <div id="vecMap" data-dojo-type="dijit.layout.ContentPane" data-dojo-props="region:'left'">  
    </div>  
    <div id="imgMap" data-dojo-type="dijit.layout.ContentPane" data-dojo-props="region:'center'">  
    </div>  
  
</div>  
</body>  
  
</html>  

 


      页面对应的样式文件为fenping.css,代码如下

html,body {  
  height:100%;  
  width:100%;  
  margin:0;  
  padding:0;  
}  
  
body {  
  background-color:#FFF;  
  color:#333;  
  font-size:14px;  
  overflow:hidden;  
  font-family:Helvetica, "Trebuchet MS", Arial, sans-serif;  
}  
  
#header {  
  border:solid 1px #224a54;  
  height:50px;  
  margin:2px;  
  background-image: url("../images/background.jpg");  
}  
  
#title {  
  color:white;  
  font-size:30px;  
  text-align:left;  
  font-weight:bolder;  
  padding-top:10px;  
  padding-left:15px;  
}  
  
#snippet {  
  font-size:14px;  
  color:#444;  
  padding-left:15px;  
}  
  
#vecMap {  
  border:solid 1px #b0c4de;  
  width:48%;  
  margin:2px;  
}  
  
#imgMap {  
  border:solid 1px #b0c4de;  
  width:48%;  
  margin:2px;  
}  
.dj_ie .infowindow .window .top .right .user .content { position: relative; }  
.dj_ie .simpleInfoWindow .content {position: relative;}  

arcgis jsapi 上一视图下一视图 Navigation可以实现切换视图

arcgis Navigation可以实现切换视图
切换到视图
 zoomToNextExtent() None Zoom to next extent in extent history.
zoomToPrevExtent() None Zoom to previous extent in extent history.
分类: ArcGIS Javascript API 2013-10-08 13:17  2515人阅读  评论(1)  收藏  举报
var map, navToolbar, editToolbar, tileLayer, toolbar;
//var mapBaseUrl = "http://localhost:8399/arcgis/rest/services/pdsTile/MapServer";
//var mapDyUrl = "http://localhost:8399/arcgis/rest/services/pds/MapServer";
//var mapDyUrl = "http://10.19.110.130:8080/arcgis/rest/services/BaseMAP/MapServer";
var mapDyUrl = "http://10.19.110.130:8080/arcgis/rest/services/baseMAP/MapServer";
var mapBjUrl = "http://10.19.110.130:8080/arcgis/rest/services/YCBJ/MapServer";
var dynamicMapServiceLayerBj;
 
 
  function init() {
    try{
     map = new esri.Map("map");
    
     //tileLayer = new esri.layers.ArcGISTiledMapServiceLayer(mapBaseUrl);
     //map.addLayer(tileLayer);
    
     var dynamicMapServiceLayer = new esri.layers.ArcGISDynamicMapServiceLayer(mapDyUrl); 
        map.addLayer(dynamicMapServiceLayer);
        
        dynamicMapServiceLayerBj = new esri.layers.ArcGISDynamicMapServiceLayer(mapBjUrl); 
        map.addLayer(dynamicMapServiceLayerBj);
    
        //初始化
        dojo.connect(map, "onLoad", dxInit);
 
 
       
    }catch(e){alert("地图初始化失败:"+e.message);}
  }
  
  function dxInit()
  {
 try{
 //alert(map.isDoubleClickZoom);
 //map.disableDoubleClickZoom(); 
      
      //比例尺显示
      //window.setTimeout("queryMapScale.init(map);", 1000);
      
      //禁止双击放大
      map.disableDoubleClickZoom();
      
      //初始化导航工具条
          navToolbar = new esri.toolbars.Navigation(map);
          dojo.connect(navToolbar, "onExtentHistoryChange", extentHistoryChangeHandler);
          
          //初始化在线编辑工具条
          editToolbar = new esri.toolbars.Edit(map);
          dojo.connect(map.graphics, "onClick", function(evt) {
              dojo.stopEvent(evt); 
              activateToolbar(evt.graphic);              
          });
          
          //初始化绘制工具条
          toolbar = new esri.toolbars.Draw(map);           
          //dojo.connect(toolbar, "onDrawEnd", addToMap);
          
          //显示坐标
          dojo.connect(map, "onMouseMove", showCoordinates);
          dojo.connect(map, "onMouseOut", hideCoordinates);          
          
          //加载鹰眼图、加载图层列表
          dojo.connect(map, "onLayerAdd", showLayers);
          
          //加载之前记录标注
          //window.setTimeout("getBz();", 1000);------------------------------
          
          //地图窗口更新
          //alert(document.getElementById('map1'));
          resizeMap();
      dojo.connect(document.getElementById('map1'), 'resize', resizeMap);
      
      //双击map,定位街景
      dojo.connect(map, 'onDblClick', zoomTo3D);
      
      //图层控制
      layersCotrol([0]);
 }catch(e){
 alert("地图初始化失败:"+e.message);
 }
  }
  
  //图层控制
  function layersCotrol(visible){
 
 try{
 dynamicMapServiceLayerBj.setVisibleLayers(visible);
 }catch(e){
 alert(e.message);
 }
  }
  
  //显示图层列表
  function showLayers(){
 
 try{
 //在下拉框中显示所有图层名称
 var layers = dynamicMapServiceLayerBj.layerInfos;
 var obj1 = new Option("", -1);
 for(var i=0; i<layers.length; i++){<="" span="">
  var obj = new Option(layers[i].name, i);
  dojo.byId("layers").add(obj);
 }
 }catch(e){
 alert(e.message);
 }
  }
  
  //选择图层
  function selectLayer(){
 
 try{
 layersCotrol([dojo.byId("layers").value]);
 }catch(e){
 alert(e.message);
 }
  }
  
  //刷新map
  function resizeMap(){
 map.resize();
 map.reposition();
  }
  
  //定位街景
  function zoomTo3D(evt)
  {
   var point = evt.mapPoint;  
   var x = point.x.toFixed(4);
   var y = point.y.toFixed(4);
 
 
   //window.top.addmark(x, y);
   //alert(x + '|' + y);
   // 定位街景
   LocationTrueMap(x, y);
  }
  // 根据坐标加载街景
  function LocationTrueMap(x, y) {
      window.top.frames["mapframe"].frames["ldframe"].showVisionByLngLat(x, y); //定位到街景
  }
  
  //鹰眼图
  function showOverview() {
      var layer = new esri.layers.ArcGISDynamicMapServiceLayer(mapDyUrl);
      layer.setImageFormat("png24");
      try{
     var createOverviewMap = function() {
       overviewMapDijit = new dijits.overview.OverviewMap({
         map: map,
         baseLayer: layer,
         width: 150,
         height: 150,
         attachTo: "bottom-right",
         expandFactor: 1.42,
         color: "#80A8C1",
         opacity: 0.5
       });
       overviewMapDijit.startup();
     };
      }catch(e){
      alert("加载鹰眼图失败:"+e.message);
      }
      
      if (layer.loaded) {
        createOverviewMap();
      }
      else {
        dojo.connect(layer, "onLoad", createOverviewMap);
      }
  }
    
  //前一视图、后一视图
  function extentHistoryChangeHandler() {
    dijit.byId("zoomprev").disabled = navToolbar.isFirstExtent();
    dijit.byId("zoomnext").disabled = navToolbar.isLastExtent();
  }
  
  //显示坐标值
  function showCoordinates(evt)
  {
   try{
       var mp = evt.mapPoint;
       dojo.byId("info").innerHTML = mp.x.toFixed(4) +","+ mp.y.toFixed(4);  
   }catch(e){
   alert("显示坐标值错误:"+e.message);
   }
  }
  
  //隐藏坐标
  function hideCoordinates(evt){
 dojo.byId("info").innerHTML = "";
  }
  
  //平移
  function pan(){
 try{
 toolbar.deactivate();
 map.setMapCursor('default'); 
 navToolbar.activate(esri.toolbars.Navigation.PAN);
 }catch(e){
 alert(e.message);
 }
  }
  
  //清空地图
  function clearMap(){
 navToolbar.deactivate();
 toolbar.deactivate();
 map.graphics.clear();
 map.setMapCursor('default');
  }
  
  //添加标注到地图方法1
  var handler;
  function addBzToMap1(){
 toolbar.deactivate();
 map.setMapCursor('crosshair'); 
 handler = dojo.connect(map, "onClick", addPoint);
  }
  
 function add(x, y) {
    
      window.parent.showdialog('add','', x,y);
  }
 
 
  function modify(id, x, y) { 
      window.parent.showdialog('modify', id, x, y);
  }
 
 
  function del(id, x, y) {
      //alert(x + "--" + y);
      window.parent.showdialog('del', id, x, y);
  }
  function addPoint(evt) {
 try{
 var symbol = new esri.symbol.PictureMarkerSymbol('images/nav/bz.png', 25, 25);
 var point = new esri.geometry.Point(evt.mapPoint, new esri.SpatialReference({ wkid: 4326 }));
 var graphic = new esri.Graphic(point, symbol);
 map.graphics.add(graphic);
 
     map.infoWindow.setTitle("新标注");
     var geoPt = evt.mapPoint;
     map.infoWindow.setContent("X坐标: " + geoPt.y.toFixed(4) 
       + "
Y坐标: " + geoPt.x.toFixed(4)
       + ""
       + "
"
     
     ); 
     map.infoWindow.show(evt.mapPoint,map.getInfoWindowAnchor(evt.screenPoint));
     map.setMapCursor('default');
     dojo.disconnect(handler);
 
 
 
 
     window.top.frames["mapframe"].frames["ldframe"].showVisionByLngLat(geoPt.x.toFixed(4), geoPt.y.toFixed(4)); //定位到街景
 }catch(e){
 alert("添加标注出错:"+e.message);
 }
  }
  
  //定位
  function zoomToPoint(x, y){
 var geoPoint = new esri.geometry.Point({"x":x,"y":y}, map.spatialReference); 
 map.centerAndZoom(geoPoint, 3);
  }
  
  //小汽车定位
  //zoomCar(113.32,23.12);
  function zoomCar(x, y) {
 navToolbar.deactivate();
 map.graphics.clear();
 try{
 var geoPoint = new esri.geometry.Point({"x":x,"y":y}, map.spatialReference); 
 map.centerAndZoom(geoPoint);
 var symbol = new esri.symbol.PictureMarkerSymbol('images/nav/car.png', 24,24);
 var graphic = new esri.Graphic(geoPoint, symbol);
 map.graphics.add(graphic);
 }catch(e){
     alert("小汽车定位" + e.message);
 }
  }
 
 
  var url = "http://192.168.1.11:8080";
  
  //接收主题名称、坐标值
  function getBz(aa) { 
      var graphicsLayer = new esri.layers.GraphicsLayer();
      try {
          for (var i = 0; i < aa.length; i++) {
              a_x = aa[i][1];
              a_y = aa[i][2];
              // alert(a_x+"---"+a_y);
              var point = new esri.geometry.Point(a_x, a_y, map.spatialReference);
              var symbol = new esri.symbol.PictureMarkerSymbol('images/nav/bz.png', 25, 25);
              var textSym = new esri.symbol.TextSymbol(aa[i][0]);
              textSym.setAlign(esri.symbol.TextSymbol.ALIGN_END);
              var graphic = new esri.Graphic(point, symbol);
 
 
              var infoTemplate = new esri.InfoTemplate();
              infoTemplate.setTitle("广告信息");
              infoTemplate.setContent(
//                "
" + url + aa[i][5] + "
" +
//                "广告名称: " + aa[i][3] + "
" +
//                "广告位置: " + aa[i][4] + "
" +
//             "
" +
//             "    "
 
 
                            );
              graphic.setInfoTemplate(infoTemplate);
              var graphicText = new esri.Graphic(point, textSym);
              graphicsLayer.add(graphic);
              graphicsLayer.add(graphicText);
 
              if (aa.length == 1) {
                //  zoomToPoint(a_x, a_y); 
              } 
          }
      } catch (e) {
          alert("获取坐标点数组出错:" + e.message + "---aa:" + aa);
      }
      map.addLayer(graphicsLayer);
  }
  
  //在线编辑--移动要素
  function activateToolbar(graphic) { 
      try{
 var tool = 0; 
     tool = tool | esri.toolbars.Edit.MOVE;
     //tool = tool | esri.toolbars.Edit.EDIT_VERTICES;  
     //tool = tool | esri.toolbars.Edit.SCALE;  
     //tool = tool | esri.toolbars.Edit.ROTATE;  
           
     var options = { 
       allowAddVertices: true, 
       allowDeleteVertices: true 
     }; 
     editToolbar.activate(tool, graphic, options);
     dojo.connect(map.graphics, "onDblClick", showInfoWindow);
      }catch(e){
      alert("移动要素问题:"+e.message);
      }
  } 
  
  function showInfoWindow(evt){
 evt.stopPropagation();
 
 map.infoWindow.setTitle("新标注");
      var geoPt = evt.mapPoint;
      map.infoWindow.setContent("X坐标: " + geoPt.y.toFixed(4) 
        + "
Y坐标: " + geoPt.x.toFixed(4)
        + ""
            + "
"
      
      ); 
      map.infoWindow.show(evt.mapPoint,map.getInfoWindowAnchor(evt.screenPoint));
  }
  
  //框选
  function queryBz()
  {
 map.setMapCursor('crosshair');
 navToolbar.deactivate();
 toolbar.activate(esri.toolbars.Draw.EXTENT);
 toolbar.onDrawEnd = function doQueryExtent(extent) {
 window.parent.stat(extent.xmin, extent.ymin, extent.xmax, extent.ymax);
//  //获取框选区域的坐标范围
//  alert("xmax:"+extent.xmax+",xmin:"+extent.xmin+",  ymax:"+extent.ymax+",ymin:"+extent.ymin);
 };
 
  }
 
ArcGIS API for JavaScript 反向地理编码(二十四)
  (2011-09-22 11:15:27)
0
转载▼
标签:  javascript
分类: JsAPI
   反向地理编码确定一个给定的点在地图上的地址。此示例演示如何做反向地理编码与ArcGIS的JavaScript API。
   反向地理编码和地理编码经常需要使用的定位器类和ArcGIS Server的地理编码服务。反向地理编码,调用locationToAddress的方法(而不是定期地理编码addressToLocations)。下面的侦听器捕获鼠标点击事件,并调用locationToAddress单击点:
dojo.connect(map, "onClick", function(evt) {
  map.graphics.clear();
  locator.locationToAddress(evt.mapPoint, 100);
});
onLocationToAddressComplete事件的侦听器传递一个回调函数AddressCandidate。然后,该函数与图形相关联的点,并把它添加到地图。该功能还使用了一个InfoTemplate的格式,点击图形时,会出现一个信息窗口。请注意,地图上的点的地址结果需要转换到屏幕点,以锚的信息窗口
screenPnt= map.toScreen(candidate.location);
map.infoWindow.show(screenPnt,map.getInfoWindowAnchor(screenPnt));
为了保持信息窗口始终可见,在信息窗口始终是从对面的象限点的地图,其中包含锚点。例如,如果在地图上右象限点在于,信息窗口出现以较低点左侧。
  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html>   <head>     <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>     <meta http-equiv="X-UA-Compatible" content="IE=7" />     <title>Find Address</title>     <link rel="stylesheet" type="text/css"     href="http://serverapi.arcgisonline.com/jsapi/arcgis/1.6/js/dojo/dijit/themes/     tundra/tundra.css">     <script type="text/javascript"     src="http://serverapi.arcgisonline.com/jsapi/arcgis/?v=1.6"></script>     <script type="text/javascript">       dojo.require("esri.map");       dojo.require("esri.tasks.locator");       function init() {         var map = new esri.Map("map", { extent: new esri.geometry.Extent (-95.2991,              38.9379-95.247638.963new esri.SpatialReference({wkid:4326})) });         var tiledMapServiceLayer = new esri.layers.ArcGISTiledMapServiceLayer                         ("http://server.arcgisonline.com/ArcGIS/rest/services/                          ESRI_StreetMap _World_2D/MapServer");         map.addLayer(tiledMapServiceLayer);         var locator = new esri.tasks.Locator                     ("http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/                      Locators/ESRI_Geocode_USA/GeocodeServer");         var infoTemplate = new esri.InfoTemplate("Location""Street: ${Address}                        <br />City: ${City}<br />State: ${State}<br />Zip: ${Zip}");         var symbol = new esri.symbol.SimpleMarkerSymbol              (esri.symbol.SimpleMarkerSymbol.STYLE_CIRCLE, 15new                             esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID,              new dojo.Color([0,0,255]), 2), new dojo.Color([0,0,255]));         dojo.connect(locator, "onLocationToAddressComplete"function(candidate) {           if (candidate.address) {             var graphic = new esri.Graphic(candidate.location, symbol,                                            candidate.address, infoTemplate);             map.graphics.add(graphic);             map.infoWindow.setTitle(graphic.getTitle());             map.infoWindow.setContent(graphic.getContent());             var screenPnt = map.toScreen(candidate.location);             map.infoWindow.show(screenPnt,map.getInfoWindowAnchor(screenPnt));           }         });         dojo.connect(map, "onClick"function(evt) {           map.graphics.clear();           locator.locationToAddress(evt.mapPoint, 100);         });       }       dojo.addOnLoad(init);     </script>   </head>   <body class="tundra">     Left click on the map to get address.     <div id="map" style="width:1200px; height:600px; border:1px solid #000;"></div>   </body> </html>

 

 

 

ArcGIS API for JavaScript 地图功能(二十二)
  (2011-09-22 10:19:56)
0
转载▼
标签: 
javascript
分类: JsAPI
  搜索您的数据使用的查找任务。样本显示的结果显示在地图上,并以表格形式使用DojoX电网。
  FindTask构造函数需要一个ArcGIS Server地图服务的URL。这个例子使用ESRI示例服务器ESRI_StatesCitiesRivers_USA服务。
如果有多个层次包含相同的字段的名称(例如“姓名”)这两个领域都将被搜索。请注意,returnGeometry设置为true,这样的结果可以显示在地图上。 findParams = new esri.tasks.FindParameters();
findParams.returnGeometry = true;findParams.layerIds = [0,1,2]; findParams.searchFields = ["CITY_NAME","NAME","SYSTEM","STATE_ABBR","STATE_NAME"];
searchText的FindParameters是什么属性将搜索。该文本输入框和发送的执行功能,当您单击“查找”按钮。该行执行任务:
 
findTask.execute(findParams,showResults);
当任务执行完毕后,showResults函数遍历在FindResult图形阵列,并增加了每个图形的地图。该功能还增加了每个网格的属性。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=7" />
    <title>Find Task</title>
    <style type="text/css">
      @import "http://serverapi.arcgisonline.com/jsapi/arcgis/1.6/js/dojo/dijit/
       themes/tundra/tundra.css";
      @import "http://serverapi.arcgisonline.com/jsapi/arcgis/1.6/js/dojo/dojox/
       grid/resources/Grid.css";
      body { font-size: 0.9em;
           font-family: Geneva, Arial, Helvetica, sans-serif;
         }
    .heading { font-weight: bold;
               padding-bottom: 0.25em;
             }
       #grid { border: 1px solid #333;
             width: 33em;
             height: 30em;
             }
    </style>
    <script type="text/javascript">djConfig={parseOnLoad:true}</script>
    <script type="text/javascript"
    src="http://serverapi.arcgisonline.com//jsapi/arcgis/?v=1.6"></script>
    <script type="text/javascript" language="Javascript">
      dojo.require("dojox.grid.DataGrid");
      dojo.require("dojo.data.ItemFileReadStore");
      dojo.require("esri.map");
      dojo.require("esri.tasks.find");

      var findTask, findParams, map;

      function init() {
          map = new esri.Map("map");
          var censusMapLayer = new esri.layers.ArcGISDynamicMapServiceLayer
                       ("http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/
                       Specialty/ESRI_StatesCitiesRivers_USA/MapServer",{id:"usa"});
          map.addLayer(censusMapLayer);

          //创建url找到目标地图服务
          findTask = new esri.tasks.FindTask
                    ("http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/
                    Specialty/ESRI_StatesCitiesRivers_USA/MapServer");

          //创建查找参数和定义已知值
          findParams = new esri.tasks.FindParameters();
          findParams.returnGeometry = true;
          findParams.layerIds = [0,1,2];
          findParams.searchFields =
                      ["CITY_NAME","NAME","SYSTEM","STATE_ABBR","STATE_NAME"];

      }


      function execute(searchText) {
        //设置搜索要查找的文本参数
        findParams.searchText = searchText;
        findTask.execute(findParams,showResults);
      }

      function showResults(results) {
       //图形标注
        var markerSymbol = new esri.symbol.SimpleMarkerSymbol
          (esri.symbol.SimpleMarkerSymbol.STYLE_SQUARE, 10, new 
          esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID,
          new dojo.Color([255,0,0]), 1), new dojo.Color([0,255,0,0.25]));
        var lineSymbol = new esri.symbol.SimpleLineSymbol
            (esri.symbol.SimpleLineSymbol.STYLE_DASH, new dojo.Color([255,0,0]), 1);
        var polygonSymbol = new esri.symbol.SimpleFillSymbol
          (esri.symbol.SimpleFillSymbol.STYLE_NONE, new  
          esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_DASHDOT,
           new dojo.Color([255,0,0]), 2), new dojo.Color([255,255,0,0.25]));
        
        //查找结果返回findResult集合.
        map.graphics.clear();
        var dataForGrid = [];
        //建立一个集合用于添加地图中找到的图形
        dojo.forEach(results,function(result){
          var graphic = result.feature;
          dataForGrid.push([result.layerName,result.foundFieldName,result.value]);
          switch (graphic.geometry.type) {
            case "point":
              graphic.setSymbol(markerSymbol);
              break;
            case "polyline":
              graphic.setSymbol(lineSymbol);
              break;
            case "polygon":
              graphic.setSymbol(polygonSymbol);
              break;
          }
          map.graphics.add(graphic);
        });
        var data={
          items:dataForGrid
        };        
        var store = new dojo.data.ItemFileReadStore({data:data});
        grid.setStore(store);
      }
      dojo.addOnLoad(init);
    </script>
  </head>
  <body class="tundra">
    <div class="heading">Find State/City/River: <input type="text" id="searchText" value="KS" />
    <input type="button" value="Find" onclick="execute(dojo.byId('searchText').value);" /></div>
    <div id="map" style="width:400px; height:300px; border:1px solid #000;"></div>
    <!--对照外地位置ID用于显示没有字段的数据-->
     <table dojotype="dojox.grid.DataGrid" jsid="grid" id="grid" style="width:400px;">
         <thead>
            <tr>
              <th field="0" width="125px">Layer Name</th>
              <th field="1" width="125px">Field Name</th>
              <th field="2" width="100%">Field Value</th>
            </tr>
          </thead>
        </table>
    </div>
  </body>
</html>
ArcGIS API for JavaScript空间参考(十)
  (2011-09-21 15:38:43)
0
转载▼
标签: 
arcgis
分类: JsAPI
 此示例演示如何定义一个自定义的范围和空间参考,当您创建一个地图。
 在版本1.0和1.1的ArcGIS JavaScript API中,您使用任何地图服务层必须符合地图的空间参考。从1.2版开始,您可以使用动态的地图服务,从地图上有不同的空间参考。虽然这给你更多的灵活性,可以使用层,投影在飞行负面影响性能。
  缓存(切片)地图图层必须匹配地图的空间参考。
  空间参考(在这种情况下,米)所使用的地图单位指定的范围内。
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=7" />
    <title>Dynamic Map Service Layer with Custom Projection and Extent</title>
    <link rel="stylesheet" type="text/css"
    href="http://serverapi.arcgisonline.com/jsapi/arcgis/1.6/js/dojo
    /dijit /themes /tundra /tundra.css">
    <script type="text/javascript"  
    src="http://serverapi.arcgisonline.com/jsapi/arcgis/?v=1.6">
    </script>

    <script type="text/javascript">
      dojo.require("esri.map");

      function init() {
        var customExtentAndSR = new esri.geometry.Extent(-20037506,- 
       9823074,20037506,10214431,new esri.SpatialReference({"wkid":54052}));
        //创建新的自定义空间参考和范围地图,该地图将在Goode Homolosina土地投影
        var map = new esri.Map("map", {extent:customExtentAndSR});
        //地图服务层有一个4325的默认空间参考
        var mapServiceLayer = new esri.layers.ArcGISDynamicMapServiceLayer
       ("http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/
        Demographics /ESRI_ Population_World/MapServer");
        map.addLayer(mapServiceLayer);
      }

      dojo.addOnLoad(init);
    </script>

  </head>
  <body>
    <div id="map" class="tundra" style="position:relative; width:1024px; height:512px; border:2px solid #000;background-color:#99CCFF;"></div>
  </body>
</html>
ArcGIS API for JavaScript鼠标悬停信息(十七)
  (2011-09-21 18:45:58)
0
转载▼
标签: 
javascript
分类: JsAPI
    该示例演示了如何显示一个信息窗口,当用户鼠标悬停在一个功能。在此示例中,该功能是一个QueryTask查询美国国家的结果。
  下面的事件监听器的格式和显示的信息窗口,当用户移动鼠标功能:
dojo.connect(map.graphics, "onMouseMove", function(evt) {
          var g = evt.graphic;
          map.infoWindow.setContent(g.getContent());
          map.infoWindow.setTitle(g.getTitle());
          map.infoWindow.show(evt.screenPoint,map.getInfoWindowAnchor(evt.screenPoint));
        });
另外一个监听器是要隐藏的窗口,一旦用户关闭该功能移动鼠标:
dojo.connect(map.graphics, "onMouseOut", function() {map.infoWindow.hide();} );
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=7" />
    <title>QueryTask with geometry, results as an InfoWindow</title>
    <link rel="stylesheet" type="text/css"
    href="http://serverapi.arcgisonline.com/jsapi/arcgis/1.6/js/dojo/dijit
    /themes/tundra/tundra.css">
    <script type="text/javascript" src="http://serverapi.arcgisonline.com/jsapi
    /arcgis/?v=1.6"></script>
    <script type="text/javascript" language="Javascript">
      dojo.require("esri.map");
      dojo.require("esri.tasks.query");

      var map, queryTask, query;
      var symbol, infoTemplate;

      function init() {
        //创建地图
        map = new esri.Map("mapDiv");

        //创建并添加层
        var layer = new esri.layers.ArcGISDynamicMapServiceLayer
        ("http://sampleserver1.arcgisonline.com/ArcGIS/rest/services
       /Specialty/ESRI_StateCityHighway_USA/MapServer");
        map.addLayer(layer);

        //监听click事件,当用户点击地图时执行executeQueryTask方法
        dojo.connect(map, "onClick", executeQueryTask);


        //建立查询任务
        queryTask = new esri.tasks.QueryTask
        ("http://sampleserver1.arcgisonline.com/ArcGIS/rest/services
        /Specialty/ESRI_StateCityHighway_USA/MapServer/1");

        //监听onComplete事件的处理结果,使用queryTask.execute方法回调
        //dojo.connect(queryTask, "onComplete", showResults);

        //建立查询过滤器
        query = new esri.tasks.Query();
        query.returnGeometry = true;
        query.outFields = ["STATE_NAME",
        "STATE_FIPS", "STATE_ABBR", "HYPERLINK", "AREA"];

        //在信息窗口创建infoTemplate
        //${属性名}将取代目前的功能和属性值.
        infoTemplate = new esri.InfoTemplate("${STATE_NAME}", "State Fips:
        ${STATE_FIPS}<br />Abbreviation: ${STATE_ABBR}<br />Area: ${AREA}");

        symbol = new esri.symbol.SimpleFillSymbol
       (esri.symbol.SimpleFillSymbol.STYLE_SOLID,
       new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_DASHDOT,
       new dojo.Color([255,0,0]), 2), new dojo.Color([255,255,0,0.5]));

      }

      function executeQueryTask(evt) {
        //用户点击onClick事件返回地图上EVT点.
        //包含在MapPoint(esri.geometry.point)和screenPoint(pixel像素点).
        //设置查询几何等于evt.mapPoint
        query.geometry = evt.mapPoint;

        //执行任务和完成showResults
        queryTask.execute(query, showResults);
      }

      function showResults(featureSet) {
        //删除地图上所有的图形层
        map.graphics.clear();

        var features = featureSet.features;

        //QueryTask返回featureSet类型.通过featureSet的循环把他们添加到信息窗口
        for (var i=0, il=features.length; i<il; i++) {
          //从featureSet中得到当前实例.
          //从当前实例赋值给graphic
          var graphic = features[0];
          graphic.setSymbol(symbol);

          //设置图形的infoTemplate.
          graphic.setInfoTemplate(infoTemplate);

          //添加当前这个图形到地图图层中
          map.graphics.add(graphic);
        }

        dojo.connect(map.graphics, "onMouseMove", function(evt) {
          var g = evt.graphic;
          map.infoWindow.setContent(g.getContent());
          map.infoWindow.setTitle(g.getTitle());
          map.infoWindow.show(evt.screenPoint,map.getInfoWindowAnchor
          (evt.screenPoint));
        });
        dojo.connect(map.graphics, "onMouseOut", function() {
            map.infoWindow.hide();
          } );

      }

      dojo.addOnLoad(init);
    </script>
  </head>
  <body class="tundra">
    Click on a state to get more info.  When state is highlighted, move mouse over state to get more info.
    <div id="mapDiv" style="width:600px; height:600px; border:1px solid #000;"></div>
  </body>
</html>
 
ArcGIS API for JavaScript实现基本的地图功能并显示地图范围(二) (2011-09-21 13:59:04)
标签:
分类:
JsAPI
   此示例检索的左下角和右上角的地图范围右下角的坐标,使用的Map.extent属性。寻找这样的地图的程度可能会更先进的东西,如平移地图到预定的“书签”,做有用的。 以下行创建的地图: var map=new esri.Map(“map”);   上述代码中出现3次"map"。 (var map)是对象的名称,第二个(esri.Map)是类的名称,和第三(“map”)是其中将包含地图的div的名称。   此示例添加了一个ArcGISTiledMapServiceLayer到地图上,代表缓存的ArcGIS Server地图服务,但你也可以使用ArcGISDynamicMapServiceLayer。您检索的方式,地图范围是相同的。   请注意,切片地图服务层的构造需要的服务的REST端点(
http://server.arcgisonline.com/ArcGIS/rest/services/ESRI_StreetMap_World_2D/MapServer)URL。   以下行添加一个事件监听器的地图onExtentChange事件: dojo.connect(map,“onExtentChange”,showExtent); 这意味着,地图范围改变时,回调函数showExtent将被调用。功能showExtent建立一个字符串,其中包含的两个角落的地图的坐标。
Lower left corner = (extent.xmin, extent.ymin)
Upper right corner = (extent.xmax, extent.ymax) 这两个角来确定地图的边界矩形,所有你需要知道的。 showExtent函数的最后一行显示在页面上添加完成字符串的“info”DIV坐标: dojo.byId("info").innerHTML= S
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html>   <head>     <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>     <meta http-equiv="X-UA-Compatible" content="IE=7" />     <title>Create Map</title>     <link rel="stylesheet" type="text/css" href="http://serverapi.arcgisonline.com/jsapi/arcgis/1.6/js/dojo/dijit/themes/tundra/tundra.css">     <script type="text/javascript" src="http://serverapi.arcgisonline.com/jsapi/arcgis/?v=1.6"></script>     <script type="text/javascript">       dojo.require("esri.map");        function init() {         var map = new esri.Map("map");         var tiledMapServiceLayer = new esri.layers.ArcGISTiledMapServiceLayer("http://server.arcgisonline.com/ArcGIS/rest/services/ESRI_StreetMap_World_2D/MapServer");         map.addLayer(tiledMapServiceLayer);         dojo.connect(map, "onExtentChange", showExtent);       }        function showExtent(extent) {         var s = "";         s = "XMin: "+ extent.xmin + "&nbsp;"            +"YMin: " + extent.ymin + "&nbsp;"            +"XMax: " + extent.xmax + "&nbsp;"            +"YMax: " + extent.ymax;         dojo.byId("info").innerHTML = s;       }        dojo.addOnLoad(init);     </script>   </head>   <body class="tundra">     <div id="map" style="width:900px; height:600px; border:1px solid #000;"></div>     <div id="info" style="padding:5px; margin:5px; background-color:#eee;"></div>     Creates a map and adds an ArcGISTiledMapServiceLayer.  On map onExtentChanged event you should see the extent printed below the map.<br />     Map navigation using mouse:     <ul>       <li>Drag to pan</li>       <li>SHIFT + Click to recenter</li>       <li>SHIFT + Drag to zoom in</li>       <li>SHIFT + CTRL + Drag to zoom out</li>       <li>Mouse Scroll Forward to zoom in</li>       <li>Mouse Scroll Backward to zoom out</li>       <li>Use Arrow keys to pan</li>       <li>+ key to zoom in a level</li>       <li>- key to zoom out a level</li>       <li>Double Click to Center and Zoom in</li>     </ul>   </body> </html>
ArcGIS API for JavaScript显示X,Y坐标(三)
  (2011-09-21 14:10:05)
0
转载▼
标签: 
arcgis
 
javascipt
分类: JsAPI
   本报告样本用户悬停鼠标指针的坐标,或拖动鼠标在地图。这是可能的事件监听器,更新的X和Y坐标移动鼠标时。
以下行创建的地图:
var map = new esri.Map("map");
   此示例添加了一个ArcGISTiledMapServiceLayer到地图上,代表缓存的ArcGIS Server地图服务,但你也可以使用ArcGISDynamicMapServiceLayer。检索的方式,你的坐标是一样的。
   这两行添加事件监听到地图中。一个侦听的OnMouseMove和其他onMouseDrag监听,但他们都调用该函数showCoordinates:
dojo.connect(map, "onMouseMove", showCoordinates);
dojo.connect(map, "onMouseDrag", showCoordinates);
这些事件都通过地图上的点坐标的showCoordinates函数。以下是的功能是如何得到的坐标,并将其写入“info”标签:
var mp = evt.mapPoint;
dojo.byId("info").innerHTML = mp.x + ", " + mp.y;
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=7" />
    <title>Create Map Display Mouse Coordinates</title>
    <link rel="stylesheet" type="text/css" href="http://serverapi.arcgisonline.com/jsapi/arcgis/1.6/js /dojo/dijit/theme /tundra
/tundra.css">
    <script type="text/javascript" src="http://serverapi.arcgisonline.com/jsapi/arcgis/?v=1.6"></script>
    <script type="text/javascript">
      dojo.require("esri.map");

      function init() {
        var map = new esri.Map("map");
        dojo.connect(map, "onLoad", function() {
          //地图加载后,监听到移动鼠标拖动事件
          dojo.connect(map, "onMouseMove", showCoordinates);
          dojo.connect(map, "onMouseDrag", showCoordinates);
        });

        var tiledMapServiceLayer = new esri.layers.ArcGISTiledMapServiceLayer("http://server.arcgisonline.com/ArcGIS/rest/services/ESRI_StreetMap_World_2D/MapServer");
        map.addLayer(tiledMapServiceLayer);
      }

      function showCoordinates(evt) {
        //从事件中得到mapPoint
        var mp = evt.mapPoint;
        //显示鼠标坐标
        dojo.byId("info").innerHTML = mp.x + ", " + mp.y;
      }

      dojo.addOnLoad(init);
    </script>
  </head>
  <body class="tundra">
   <div id="map" style="position:relative; width:900px; height:600px; border:1px solid #000;">
     <span id="info" style="position:absolute; right:25px; bottom:5px; color:#000; z-index:50;"></span>
   </div>
  </body>
</html>

 

ArcGIS API for JavaScript地图属性(十一)
  (2011-09-21 16:06:22)
0
转载▼
标签: 
javascript
分类: JsAPI
  此示例演示如何读地图和图层属性和报告的信息返回给用户。示例中的四个按钮允许您检索地图属性。每个按钮调用不同的功能。
  所有图层 - 此按钮调用的函数getMapLayers,遍历每一层地图和报告层ID,能见度,并在警告框显示。
  空间参考 - 这个按钮调用函数getSR,报告警告框,地图的空间参考ID(WKID)。
  比例级别 - 此按钮调用函数getScales,报告每个portlandParcels切片地图服务层的规模信息。该函数使用ArcGISTiledMapServiceLayer.tileInfo的属性,它可以显示你在地图缓存多少比例级别,他们是什么尺度,以及大小比例。
地图的宽度高度 - 此按钮调用该函数的getMapWidthHeight,报告一个警告框显示地图的宽度和高度。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=7" />
    <title>ArcGIS JavaScript API Map Layer</title>
    <link rel="stylesheet" type="text/css"
    href="http://serverapi.arcgisonline.com/jsapi/arcgis/1.6/js/dojo/dijit/themes/tundra
    /tundra.css">
    <script type="text/javascript" src="http://serverapi.arcgisonline.com/jsapi/arcgis
    /?v=1.6"></script>
    <script type="text/javascript">
      dojo.require("esri.map");

      var myMap, portlandParcels, transportation, census;

      function init() {
        myMap = new esri.Map("mapDiv");

        portlandParcels = new esri.layers.ArcGISTiledMapServiceLayer
       ("http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Portland/Portland_
        ESRI_LandBase_AGO/MapServer");
        myMap.addLayer(portlandParcels);

        transportation = new esri.layers.ArcGISTiledMapServiceLayer
       ("http://server.arcgisonline.com/ArcGIS/rest/services/Reference/ESRI_Transportation
        _World_2D/MapServer", {"id":"agoreference", "opacity":0.5});
        myMap.addLayer(transportation);

        census = new esri.layers.ArcGISDynamicMapServiceLayer
        ("http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Demographics/ESRI_Census
        _USA/MapServer", {"id":"census","opacity":0.5});
        myMap.addLayer(census);
      }

      function getMapLayers() {
        for (var j=0, jl=myMap.layerIds.length; j<jl; j++) {
          var currentLayer = myMap.getLayer(myMap.layerIds[j]);
          alert("id: " + currentLayer.id + ", visible: " + currentLayer.visible + ",
          opacity: " + currentLayer.opacity);
        }
      }

      function getSr() {
        alert("Spatial Reference WKID: " + myMap.spatialReference.wkid);
      }

      function getScales() {
        var tileInfo = portlandParcels.tileInfo;
        var scales = "";
        for (var j=0, jl=tileInfo.lods.length; j<jl; j++) {
          var level = tileInfo.lods[j].level;
          var scale = tileInfo.lods[j].scale;
          var resolution = tileInfo.lods[j].resolution;

          scales = scales + "level: " + level + ", scale: " + scale + ", resolution: " +
          resolution + "\n";
        }
        alert(scales);
      }

      function getMapWidthHeight() {
        alert("Width = " + myMap.width + "; Height = " + myMap.height);
      }

      dojo.addOnLoad(init);
    </script>
  </head>
  <body class="tundra">
    <div id="mapDiv" style="width:900px; height:600px; border:1px solid #000;"></div>
    Simple example illustrating working with map and layer properties<br />
    <input type="button" value="所有图层" onclick="getMapLayers()" />
    <input type="button" value="空间参考" onclick="getSr()" />
    <input type="button" value="比例级别" onclick="getScales()" />
    <input type="button" value="地图的宽度高度" onclick="getMapWidthHeight()" /> <br />
  </body>
</html>
分类: 编程 帮助 2014-04-24 16:47  2079人阅读  评论(0)  收藏  举报
在之前的实验中,距离量算跟面积量算一直出问题,费了很长的时间,各种调式找不到原因。现在成功完成,与君共勉
1、距离量算中        lengthParams.polylines = [geometry];
2、面积量算中        this.outSR = new esri.SpatialReference({ wkid: 102113 });
        geometryService.project([geometry], this.outSR, function (geometry) {
            geometryService.simplify(geometry, function (simplifiedGeometries) {
                areasAndLengthParams.polygons = simplifiedGeometries;
                areasAndLengthParams.polygons[0].spatialReference = new esri.SpatialReference(102113);
                geometryService.areasAndLengths(areasAndLengthParams);
            });
        });
还有面积量算中跟距离量算有所不同,需要进行投影变换!因为一般咱们的底图坐标系为4326
 
 
[csharp]  view plain copy
0
0
  1. //量测  
  1. function measutreLength() {  
  1.     toolbar.activate(esri.toolbars.Draw.POLYLINE);  
  1. }  
  1. function measutreArea() {  
  1.     toolbar.activate(esri.toolbars.Draw.POLYGON);  
  1. }  
 
//量测  
function measutreLength() {  
    toolbar.activate(esri.toolbars.Draw.POLYLINE);  
}  
function measutreArea() {  
    toolbar.activate(esri.toolbars.Draw.POLYGON);  
}  

[csharp]  view plain copy


//量算  
function doMeasure(geometry) {  
    //更加类型设置显示样式  
    measuregeometry = geometry;   
    toolbar.deactivate();  
    switch (geometry.type) {  
        case "polyline":  
            var symbol = new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([0, 0, 0]), 2);  
            break;  
        case "polygon":  
            var symbol = new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_NONE, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_DASHDOT, new dojo.Color([255, 0, 0]), 2), new dojo.Color([255, 255, 0, 0.25]));  
            break;  
    }  
    //设置样式  
    var graphic = new esri.Graphic(geometry,symbol);  
    //清除上一次的画图内容  
    myMap.graphics.clear();  
    myMap.graphics.add(graphic);  
    //进行投影转换,完成后调用projectComplete  
    MeasureGeometry(geometry);  
}  
  
//投影转换完成后调用方法  
function MeasureGeometry(geometry) {  
    //如果为线类型就进行lengths距离测算  
    if (geometry.type == "polyline") {  
        var lengthParams = new esri.tasks.LengthsParameters();  
        lengthParams.polylines = [geometry];  
        lengthParams.lengthUnit = esri.tasks.GeometryService.UNIT_METER;  
        lengthParams.geodesic true;  
        lengthParams.polylines[0].spatialReference = new esri.SpatialReference(4326);  
        geometryService.lengths(lengthParams);  
        dojo.connect(geometryService, "onLengthsComplete", outputDistance);  
    }  
    //如果为面类型需要先进行simplify操作在进行面积测算  
    else if (geometry.type == "polygon") {  
        var areasAndLengthParams = new esri.tasks.AreasAndLengthsParameters();  
        areasAndLengthParams.lengthUnit = esri.tasks.GeometryService.UNIT_METER;  
        areasAndLengthParams.areaUnit = esri.tasks.GeometryService.UNIT_SQUARE_METERS;  
        this.outSR = new esri.SpatialReference({ wkid: 102113 });  
        geometryService.project([geometry], this.outSR, function (geometry) {  
            geometryService.simplify(geometry, function (simplifiedGeometries) {  
                areasAndLengthParams.polygons = simplifiedGeometries;  
                areasAndLengthParams.polygons[0].spatialReference = new esri.SpatialReference(102113);  
                geometryService.areasAndLengths(areasAndLengthParams);  
            });  
        });  
        dojo.connect(geometryService, "onAreasAndLengthsComplete", outputAreaAndLength);  
    }  
}  
  
//显示测量距离  
function outputDistance(result) {  
    var CurX = measuregeometry.paths[0][measuregeometry.paths[0].length - 1][0];  
    var CurY = measuregeometry.paths[0][measuregeometry.paths[0].length - 1][1];  
    var  CurPos  =  new  esri.geometry.Point(CurX,  CurY, myMap.spatialReference);  
    myMap.infoWindow.setTitle("距离测量");  
    myMap.infoWindow.setContent(" 测 量 长 度 : <strong>" + parseInt(String(result.lengths[0])) + "米</strong>");  
    myMap.infoWindow.show(CurPos);  
}  
  
//显示测量面积  
function outputAreaAndLength(result) {  
    var CurX = (measuregeometry._extent.xmax + measuregeometry._extent.xmin) / 2;  
    var CurY = (measuregeometry._extent.ymax + measuregeometry._extent.ymin) / 2  
    var CurPos = new esri.geometry.Point(CurX, CurY, myMap.spatialReference);  
    myMap.infoWindow.setTitle("面积测量");  
    myMap.infoWindow.setContent(" 面积 : <strong>" + parseInt(String(result.areas[0])) + "平方米</strong> 周长:" + parseInt(String(result.lengths[0])) + "米");  
    myMap.infoWindow.show(CurPos);  
    //alert("面积:" + dojo.number.format(result.areas[0]) + "平方米" + " 长度:" + dojo.number.format(result.lengths[0]) + "米");  
}  

 

  此示例演示如何,您可以设置地图范围层的样式。样本有两个层次:从ArcGISOnline的ArcGISTiledMapServiceLayer,涵盖了整个世界。代码包含两个事件侦听器,每一层。监听已加载了多少层。当层数达到2,createMapAddLayers函数被调用。
myMap = new esri.Map("mapDiv", { extent:myService2.fullExtent });
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=7" />
    <title>Set Map Extent Using Second Service</title>
    <link rel="stylesheet" type="text/css"      
    href="http://serverapi.arcgisonline.com/jsapi/arcgis/1.6/js/dojo/dijit
    /themes /tundra /tundra.css">
    <script type="text/javascript"  
    src="http://serverapi.arcgisonline.com/jsapi/arcgis/
    ?v=1.6"></script>
    <script type="text/javascript">
      dojo.require("esri.map");
      var myMap, myService1, myService2;

      function initLayers() {
        var primaryMapServiceURL = "http://server.arcgisonline.com
        /ArcGIS/rest/services/ESRI_StreetMap_World_2D/MapServer";
        myService1 = new esri.layers.ArcGISTiledMapServiceLayer
        (primaryMapServiceURL);

        var secondaryMapServiceURL = "http://sampleserver1.arcgisonline.com
        /ArcGIS/rest/services/Petroleum/KGS_OilGasFields_Kansas/MapServer";
        myService2 = new esri.layers.ArcGISDynamicMapServiceLayer
        (secondaryMapServiceURL, {opacity:0.75});

        var layerLoadCount = 0;
        //当两个层加载时运行createMapAddLayers

        if (myService1.loaded) {
          layerLoadCount += 1;
          if (layerLoadCount === 2) {
            createMapAddLayers(myService1,myService2);
          }
        } else {
          dojo.connect(myService1, "onLoad", function(service) {
            layerLoadCount += 1;
            if (layerLoadCount === 2) {
              createMapAddLayers(myService1,myService2);
            }
          });
        }

        if (myService2.loaded) {
          layerLoadCount += 1;
          if (layerLoadCount === 2) {
            createMapAddLayers(myService1,myService2);
          }
        } else {
          dojo.connect(myService2, "onLoad", function(service) {
            layerLoadCount += 1;
            if (layerLoadCount === 2) {
              createMapAddLayers(myService1,myService2);
            }
          });
        }
      }

      //创建一个地图,设置范围并添加到地图服务中
      function createMapAddLayers(myService1,myService2) {
        //创建地图
        myMap = new esri.Map("mapDiv", { extent:myService2.fullExtent });
        myMap.addLayer(myService1);
        myMap.addLayer(myService2);
      }

      dojo.addOnLoad(initLayers);
    </script>
  </head>
  <body class="tundra">
    <div id="mapDiv" style="width:600px; height:400px; border:1px solid #000;"></div>
    <br/>
    This map shows two services:
    <ul>
    <li>An ArcGIS Online tiled service that has a world extent.</li>
    <li>A second dynamic service with an extent of the State of Kansas.  This is the extent used when the maps are first displayed. </li>
    </ul>

    Note that if you want to combine to tiled services in the same map, they must have the same tile configuration.
  </body>
</html>

 

 右键菜单
<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">
    <title>Context Menu for Map and Graphics</title>


    <link rel="stylesheet" href= "http://js.arcgis.com/3.14/dijit/themes/claro/claro.css">
    <link rel="stylesheet" href="http://js.arcgis.com/3.14/esri/css/esri.css">
    <style>
      html, body {
        height:100%;
        margin: 0;
        padding: 0;
        width:100%;
        overflow:hidden;
      }
      #header {
        overflow:hidden;
        height: 1.6em;
      }
      div.insetType {
        color: #97F900;
        font-size: 24px;
        font-family: Rockwell, Georgia, "Times New Roman", Times, serif;
        padding-left: 25px;
      }
    </style>


    <script src="http://js.arcgis.com/3.14/"></script>
    <script>
      var map, editToolbar, ctxMenuForGraphics, ctxMenuForMap;
      var selected, currentLocation;
      
      require([
        "esri/map", "esri/geometry/Point", "esri/geometry/Polygon", 
        "esri/toolbars/draw", "esri/toolbars/edit",
        "esri/symbols/SimpleMarkerSymbol", "esri/symbols/SimpleLineSymbol",
        "esri/symbols/SimpleFillSymbol",
        "esri/graphic", "esri/geometry/jsonUtils",
        "esri/Color", "dojo/parser",
        "dijit/Menu", "dijit/MenuItem", "dijit/MenuSeparator",
        
        "dijit/form/Button", "dijit/layout/BorderContainer", "dijit/layout/ContentPane", 
        "dojo/domReady!"
      ], function(
        Map, Point, Polygon, 
        Draw, Edit,
        SimpleMarkerSymbol, SimpleLineSymbol, 
        SimpleFillSymbol,
        Graphic, geometryJsonUtils,
        Color, parser,
        Menu, MenuItem, MenuSeparator
      ) {
        parser.parse();


        map = new Map("map", {
          basemap: "satellite",
          center: [20.039, 62.739],
          zoom: 3
        });
        map.on("load", createToolbarAndContextMenu);


        function createToolbarAndContextMenu() {
          // Add some graphics to the map
          addGraphics();


          // Create and setup editing tools
          editToolbar = new Edit(map);


          map.on("click", function(evt) {
            editToolbar.deactivate();
          });


          createMapMenu();
          createGraphicsMenu();
        }


        function createMapMenu() {
          // Creates right-click context menu for map
          ctxMenuForMap = new Menu({
            onOpen: function(box) {
              // Lets calculate the map coordinates where user right clicked.
              // We'll use this to create the graphic when the user clicks
              // on the menu item to "Add Point"
              currentLocation = getMapPointFromMenuPosition(box);          
              editToolbar.deactivate();
            }
          });


          ctxMenuForMap.addChild(new MenuItem({ 
            label: "Add Point",
            onClick: function(evt) {
              var symbol = new SimpleMarkerSymbol(
                SimpleMarkerSymbol.STYLE_SQUARE, 
                30, 
                new SimpleLineSymbol(
                  SimpleLineSymbol.STYLE_SOLID, 
                  new Color([200,235, 254, 0.9]), 
                  2
                ), new Color([200, 235, 254, 0.5]));
              var graphic = new Graphic(geometryJsonUtils.fromJson(currentLocation.toJson()), symbol);
              map.graphics.add(graphic);
            }
          }));


          ctxMenuForMap.startup();
          ctxMenuForMap.bindDomNode(map.container);
        }


        function createGraphicsMenu() {
          // Creates right-click context menu for GRAPHICS
          ctxMenuForGraphics = new Menu({});
          ctxMenuForGraphics.addChild(new MenuItem({ 
            label: "Edit",
            onClick: function() {
              if ( selected.geometry.type !== "point" ) {
                editToolbar.activate(Edit.EDIT_VERTICES, selected);
              } else {
                alert("Not implemented");
              }
            } 
          }));


          ctxMenuForGraphics.addChild(new MenuItem({ 
            label: "Move",
            onClick: function() {
              editToolbar.activate(Edit.MOVE, selected);
            } 
          }));


          ctxMenuForGraphics.addChild(new MenuItem({ 
            label: "Rotate/Scale",
            onClick: function() {
            if ( selected.geometry.type !== "point" ) {
                editToolbar.activate(Edit.ROTATE | Edit.SCALE, selected);
              } else {
                alert("Not implemented");
              }
            }
          }));


          ctxMenuForGraphics.addChild(new MenuItem({ 
            label: "Style",
            onClick: function() {
              alert("Not implemented");
            }
          }));
        
          ctxMenuForGraphics.addChild(new MenuSeparator());
          ctxMenuForGraphics.addChild(new MenuItem({ 
            label: "Delete",
            onClick: function() {
              map.graphics.remove(selected);
            }
          }));


          ctxMenuForGraphics.startup();


          map.graphics.on("mouse-over", function(evt) {
            // We'll use this "selected" graphic to enable editing tools
            // on this graphic when the user click on one of the tools
            // listed in the menu.
            selected = evt.graphic;


            // Let's bind to the graphic underneath the mouse cursor           
            ctxMenuForGraphics.bindDomNode(evt.graphic.getDojoShape().getNode());
          });


          map.graphics.on("mouse-out", function(evt) {
            ctxMenuForGraphics.unBindDomNode(evt.graphic.getDojoShape().getNode());
          });
        }


        // Helper Methods
        function getMapPointFromMenuPosition(box) {
          var x = box.x, y = box.y;
          switch( box.corner ) {
            case "TR":
              x += box.w;
              break;
            case "BL":
              y += box.h;
              break;
            case "BR":
              x += box.w;
              y += box.h;
              break;
          }


          var screenPoint = new Point(x - map.position.x, y - map.position.y);
          return map.toMap(screenPoint);
        }
        
        function addGraphics() {
          // Adds pre-defined geometries to map
          var polygonSymbol = new SimpleFillSymbol(
            SimpleFillSymbol.STYLE_SOLID, 
            new SimpleLineSymbol(
              SimpleLineSymbol.STYLE_DOT, 
              new Color([151, 249, 0, 0.8]),
              3
            ), 
            new Color([151, 249, 0, 0.45])
          );
          
          var polygon = new Polygon({
            "rings": [
              [
                [-4226661.916056009, 8496372.808143634],
                [-3835304.3312360067, 8731187.359035634],
                [-2269873.991956003, 9005137.668409634],
                [-1213208.5129420012, 8613780.083589634],
                [-1017529.7205320001, 8065879.464841632],
                [-1213208.5129420012, 7478843.087611631],
                [-2230738.233474003, 6891806.710381631],
                [-2935181.8861500043, 6735263.6764536295],
                [-3522218.263380006, 6891806.710381631],
                [-3952711.606682008, 7165757.01975563],
                [-4265797.674538009, 7283164.295201631],
                [-4304933.433020009, 7635386.121539632],
                [-4304933.433020009, 7674521.880021632],
                [-4226661.916056009, 8496372.808143634]
              ]
            ],
            "spatialReference": {
              "wkid": 102100
            }
          });
          var arrow = new Polygon({
            "rings": [
              [
                [9862211.137464028, 6617856.40100763],
                [8922952.933896024, 5522055.163511626],
                [8922952.933896024, 5991684.265295628],
                [6105178.323192019, 5991684.265295628],
                [6105178.323192019, 7087485.50279163],
                [8922952.933896024, 7087485.50279163],
                [8922952.933896024, 7557114.604575632],
                [9862211.137464028, 6617856.40100763]
              ]
            ],
            "spatialReference": {
              "wkid": 102100
            }
          });


          var triangle = new Polygon({
            "rings": [
              [
                [2426417.02588401, 8535508.566625634],
                [4304933.433020014, 12292541.380897645],
                [6183449.840156019, 8535508.566625634],
                [2426417.02588401, 8535508.566625634]
              ]
            ],
            "spatialReference": {
              "wkid": 102100
            }
          });


          map.graphics.add(new Graphic(polygon, polygonSymbol));
          map.graphics.add(new Graphic(arrow, polygonSymbol));
          map.graphics.add(new Graphic(triangle, polygonSymbol));
        }
      });
    </script>
  </head>
  <body class="claro" style="font-size: 0.75em;">
    <div data-dojo-type="dijit/layout/BorderContainer" 
         data-dojo-props="design:'headline', gutters:false" 
         style="width:100%;height:100%;">


      <div id="header" 
            data-dojo-type="dijit/layout/ContentPane" 
            data-dojo-props="region:'top'"> 


        <div class="insetType">Right-click on map or graphic to view context menu</div>


      </div>


      <div id="map" data-dojo-type="dijit/layout/ContentPane" data-dojo-props="region:'center'" ></div>


    </div>
  </body>
</html>

 

该例展示了加载基础底图的方法。例子中采用ArcGIS Online中的缓存服务,地图范围设置为San Francisco,控制代码如下:
   var initExtent= newesri.geometry.Extent({"xmin":-13635568.034589134,"ymin":4541606.359162286,"xmax":-13625430.573712826,"ymax":4547310.472398059,"spatialReference":{"wkid":102100}});  
 map = new esri.Map("map",{extent:initExtent});
如果想更改初始地图显示范围,可利用浏览器的开发者工具获取范围,以IE  9为例,步骤如下:
运行该应用程序
将地图缩放到理想范围
按F2,在如下图弹出的界面中切换到控制台标签,
输入dojo.toJson(map.extent.toJson());
复制该段代码,替换initExtent 中相应内容。

例子代码如下:
[html] view plaincopy

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">  
<html>  
  <head>  
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">  
    <meta http-equiv="X-UA-Compatible" content="IE=7,IE=9" />  
    <!--The viewport meta tag is used to improve the presentation and behavior of the samples   
      on iOS devices-->  
    <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no"/>  
    <title>Topographic Map</title>  
    <link rel="stylesheet" type="text/css" href="http://serverapi.arcgisonline.com/jsapi/arcgis/2.8/js/dojo/dijit/themes/claro/claro.css">  
    <style>  
      html, body { height: 100%; width: 100%; margin: 0; padding: 0; }  
      .esriScalebar{  
        padding: 20px 20px;  
      }  
      #map{  
        padding:0;  
      }  
    </style>  
    <script type="text/javascript">var djConfig = {parseOnLoad: true};</script>  
    <script type="text/javascript" src="http://serverapi.arcgisonline.com/jsapi/arcgis/?v=2.8"></script>  
    <script type="text/javascript">  
      dojo.require("dijit.layout.BorderContainer");  
      dojo.require("dijit.layout.ContentPane");  
      dojo.require("esri.map");  
  
        
      var map;  
  
      function init() {  
        var initExtent = new esri.geometry.Extent({"xmin":-122.46,"ymin":37.73,"xmax":-122.36,"ymax":37.77,"spatialReference":{"wkid":4326}});  
        map = new esri.Map("map",{  
          extent:esri.geometry.geographicToWebMercator(initExtent)  
        });  
        //Add the topographic layer to the map. View the ArcGIS Online site for services http://arcgisonline/home/search.html?t=content&f=typekeywords:service      
        var basemap = new esri.layers.ArcGISTiledMapServiceLayer("http://server.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer");  
        map.addLayer(basemap);  
  
        dojo.connect(map, 'onLoad', function(theMap) {   
          //resize the map when the browser resizes  
          dojo.connect(dijit.byId('map'), 'resize', map,map.resize);  
        });  
      }  
  
      dojo.addOnLoad(init);  
    </script>  
  </head>  
    
  <body class="claro">  
    <div dojotype="dijit.layout.BorderContainer" design="headline" gutters="false" style="width: 100%; height: 100%; margin: 0;">  
      <div id="map" dojotype="dijit.layout.ContentPane" region="center" style="border:1px solid #000;padding:0;">  
     </div>  
    </div>  
  </body>  
  
</html>   

 

posted @ 2022-08-03 10:27  devgis  阅读(317)  评论(0编辑  收藏  举报