Drag Graphics Point and Drop at New Location

14854
17
04-18-2011 03:37 PM
ManishGohil
New Contributor III
Hello All,
  We have our application developed in .Net using WebADF Map controls.
  I need help on how i can implement the "drag graphics point" functionality in our application that built using WebADF.Net controls.
I found that using dojo we can implement drag/drop but i am not able to use dojo with Map control of WebADF.
I also want to know what are the different approach/implementation for drag/drop graphics on Map?
Any help will be appreciated.

One similar post that never replied :
http://forums.esri.com/Thread.asp?c=158&f=2396&t=286884

Thanks
Lala Rabari
0 Kudos
17 Replies
HemingZhu
Occasional Contributor III
Hello All,
  We have our application developed in .Net using WebADF Map controls.
  I need help on how i can implement the "drag graphics point" functionality in our application that built using WebADF.Net controls.
I found that using dojo we can implement drag/drop but i am not able to use dojo with Map control of WebADF.
I also want to know what are the different approach/implementation for drag/drop graphics on Map?
Any help will be appreciated.

One similar post that never replied :
http://forums.esri.com/Thread.asp?c=158&f=2396&t=286884

Thanks
Lala Rabari


In JS api it is very easy to drag and drop a gaphic by invoking a couple of event. Here is the sample page from ESRI, I just change a little bit. Try it youself if you are interested.

<!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" />
    <!--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>Draw and drop Point</title>
    <link rel="stylesheet" type="text/css" href="http://serverapi.arcgisonline.com/jsapi/arcgis/2.2/js/dojo/dijit/themes/claro/claro.css" />
    <script type="text/javascript" src="http://serverapi.arcgisonline.com/jsapi/arcgis/?v=2.2"></script>
    <script type="text/javascript">
      dojo.require("esri.map");
      dojo.require("esri.toolbars.draw");
      dojo.require("esri.tasks.query");

      //global variables
      var map, defaultSymbol, highlightSymbol, resultTemplate;
      var theGraphic;

      function init() {
        //create map, set initial extent and disable default info window behavior
        map = new esri.Map("map", {
          extent: esri.geometry.geographicToWebMercator(new esri.geometry.Extent(-125.90, 44.60, -114.65, 50.22, new esri.SpatialReference({wkid:4326}))),
          showInfoWindowOnClick:false
        });
        dojo.connect(map, "onLoad", function(map) {
            dojo.connect(dijit.byId('map'), 'resize', resizeMap);
        });
        map.addLayer(new esri.layers.ArcGISTiledMapServiceLayer("http://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer"));

        //initialize symbology
        defaultSymbol = new esri.symbol.SimpleMarkerSymbol().setColor(new dojo.Color([0,0,255]));
        highlightSymbol = new esri.symbol.SimpleMarkerSymbol().setColor(new dojo.Color([255,0,0]));

        //initialize & execute query
        var queryTask = new esri.tasks.QueryTask("http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Specialty/ESRI_StatesCitiesRivers_USA/Map...");
        var query = new esri.tasks.Query();
        query.where = "STATE_NAME = 'Washington'";
        query.outSpatialReference = {wkid:102100};
        query.returnGeometry = true;
        query.outFields = ["CITY_NAME"];
        queryTask.execute(query, addPointsToMap);
        //info template for points returned
        resultTemplate = new esri.InfoTemplate("City", "<tr><td>${CITY_NAME}</tr></td>");   
       }
       function resizeMap() {
           var resizeTimer;
           clearTimeout(resizeTimer);
           resizeTimer = setTimeout(function() {
               map.resize();
               map.reposition();
           }, 500);
       }
      //add points to map and set their symbology + info template
      function addPointsToMap(featureSet) {
        dojo.forEach(featureSet.features,function(feature){
          map.graphics.add(feature.setSymbol(defaultSymbol).setInfoTemplate(resultTemplate));
        });
        dojo.connect(map.graphics, "onMouseDown", holdGraphic);
        dojo.connect(map, "onMouseDragEnd", releaseGraphic);
      }
      function holdGraphic(evt) {
          map.disablePan();
          theGraphic = evt.graphic;
          theGraphic.setSymbol(highlightSymbol); 
      }
      function releaseGraphic(evt) {
          theGraphic.geometry = evt.mapPoint;
          theGraphic.setSymbol(defaultSymbol);
          map.disablePan();
      }
      //find all points within argument extent
      function findPointsInExtent(extent) {
        var results = [];
        dojo.forEach(map.graphics.graphics,function(graphic){
          if (extent.contains(graphic.geometry)) {
            graphic.setSymbol(highlightSymbol);
            results.push(graphic.getContent());
          }
          //else if point was previously highlighted, reset its symbology
          else if (graphic.symbol == highlightSymbol) {
            graphic.setSymbol(defaultSymbol);
          }
        });
  
        //display number of points in extent
        dojo.byId("inextent").innerHTML = results.length;

        //display list of points in extent
        dojo.byId("results").innerHTML = "<table><tbody>" + results.join("") + "</tbody></table>";
      }

      dojo.addOnLoad(init);
    </script>

  </head>
  <body class="claro">
    Draw an Extent on the map to find all points within this extent
    <!-- map div -->
    <div id="map" style="width:800px; height:400px; border:1px solid #000;"></div>
    <br />
  </body>
</html>
0 Kudos
SteveLi
New Contributor
Where can I find the original sample code?  I couldn't find it in the javascript api samples.

Thanks.
0 Kudos
HemingZhu
Occasional Contributor III
Where can I find the original sample code?  I couldn't find it in the javascript api samples.

Thanks.


The orignal sample is at: http://help.arcgis.com/en/webapi/javascript/arcgis/demos/graphics/graphics_extent_query.html. I just changed it a liitle bit for Drag and drop purpose.
0 Kudos
derekswingley1
Frequent Contributor
There's an easier way to do this. I think the code below was originally posted in the old forums but I've hung on to it for a while:
<!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>Moving a marker</title> 
    
    <link rel="stylesheet" type="text/css" href="http://serverapi.arcgisonline.com/jsapi/arcgis/2.2/js/dojo/dijit/themes/tundra/tundra.css"> 
    <script type="text/javascript" src="http://serverapi.arcgisonline.com/jsapi/arcgis/?v=2.2"></script> 
    
    <script type="text/javascript"> 
      dojo.require("esri.map");
      dojo.require("dojox.gfx.move");
 
      dojo.addOnLoad(init);
 
      var map;
      
      function init() {
        map = new esri.Map("map");
        dojo.connect(map, "onLoad", onMapLoad);
        
        var tiledMapServiceLayer = new esri.layers.ArcGISTiledMapServiceLayer("http://server.arcgisonline.com/ArcGIS/rest/services/ESRI_Imagery_World_2D/MapServer");
        map.addLayer(tiledMapServiceLayer);
      }
      
      function onMapLoad() {
        var geometry = map.extent.getCenter().offset(0, 15);
        var symbol = new esri.symbol.SimpleMarkerSymbol().setColor("red");
        var graphic = new esri.Graphic(geometry, symbol);
        
        // Add a graphic
        map.graphics.add(graphic);
 
        // Make the shape moveable
        var dojoShape = graphic.getDojoShape();
        var moveable = new dojox.gfx.Moveable(dojoShape);
        
        // Update the geometry at the end of move
        var moveStopToken = dojo.connect(moveable, "onMoveStop", function(mover) {
          // Get the transformation that was applied to 
          // the shape since the last move
          var tx = dojoShape.getTransform();
          
          var startPoint = graphic.geometry;
          var endPoint = map.toMap(map.toScreen(startPoint).offset(tx.dx, tx.dy));
          
          // clear out the transformation
          dojoShape.setTransform(null);
          
          // update the graphic geometry
          graphic.setGeometry(endPoint);
          
          // You can find quite a bit of information about
          // applying transformations to Dojo gfx shapes in this
          // document:
          // http://docs.dojocampus.org/dojox/gfx#coordinates-and-transformations
        });
      }
    </script> 
 
  </head> 
  <body class="tundra"> 
    <p> 
    </p> 
 
    <div id="map" style="width:700px; height:500px; border:1px solid #000;"></div> 
  </body> 
</html>
0 Kudos
HemingZhu
Occasional Contributor III
Where can I find the original sample code?  I couldn't find it in the javascript api samples.

Thanks.


All i  have to add to the sample code is the following. So make your own judgement what is best for you.

dojo.connect(map.graphics, "onMouseDown", holdGraphic);
dojo.connect(map, "onMouseDragEnd", releaseGraphic);
.....

function holdGraphic(evt) {
map.disablePan();
theGraphic = evt.graphic;
theGraphic.setSymbol(highlightSymbol);
}
function releaseGraphic(evt) {
theGraphic.geometry = evt.mapPoint;
theGraphic.setSymbol(defaultSymbol);
map.disablePan();
}
0 Kudos
derekswingley1
Frequent Contributor
Maybe "easier" was the wrong word...

I think seeing the point move as you drag it provides a better user experience.
0 Kudos
ManishGohil
New Contributor III
Hi guys thanks for the reply.
Using Heming code the drag/drop graphic functionality is working.
But there is one more question i put in the original forum regarding .Net Web ADF,in our application we don't use dojo directly for Map display and for drawing graphics instead we use Web ADF Web control and framework classes to do that.
Can any one answer how can i use dojo in combination with Web ADF to achieve drag/drop? ,because application uses Web ADF extensively

Thanks in advance
Lala Rabari
0 Kudos
ManishGohil
New Contributor III
Hello guys,
Actually my goal was to achieve this functionality using Web ADF JavaScript not using the ArcGIS JavaScript i.e dojo.
I got success in implementing drag graphics functionality with the real user experience when user dragging the graphics.

I am posting my code here if it help someone :

ar map;
var mapID = 'Map1';
var graphicCount = 0;
var drawstopflag = false;
var drawRouteFlag = false;
var maptipTitle;
var dragMode = false;

function initialize() {
    // $find is a shortcut method offered by the ASP.NET AJAX JavaScript Library for
    // retrieving JavaScript objects that have been registered as components with the
    // AJAX framework (i.e. either by having been created via $create or explicitly 
    // registered via Sys.Application.addComponent
    map = $find(mapID);

    // map.add_onProgress(customProgress);
    // Show map coordinates in status bar based on cursor location
    map.add_mouseMove(mouseMove);

    map.add_mouseDragCompleted(mouseDragCompleted);
    map.add_mouseDragging(mouseDragging);
    if (drawRouteFlag) {
        drawRoute();
        drawGeometry(geom, "Route");
    }
   
    if (drawstopflag) {
        drawstops();
    }

    

}



var thegraphic;
function mouseDragging(sender, eventArgs) {
   // if (ESRI.ADF.Geometries.Point.isInstanceOfType(eventArgs.element.get_geometry())) {
        if (currentelement != null) {
            currentelement.set_geometry(eventArgs.coordinate);
            // currentelement._parent.get_mapTips()._currentHighlight.set_geometry(evenArgs.coordinate);
            // map.refresh();
        }
   // }

}
function mouseDragCompleted(sender, evenArgs) {
    var tool = $find("Toolbar1");
   // if (ESRI.ADF.Geometries.Point.isInstanceOfType(eventArgs.element.get_geometry())) {
        if (currentelement != null) {
            currentelement.set_geometry(evenArgs.coordinate);
            if (ESRI.ADF.Geometries.Point.isInstanceOfType(currentelement.get_geometry()) & currentelement._attributes["FeatureId"] == "dragStop") {
                __doPostBack("Map1Drag", evenArgs.coordinate.coordinates[0] + '#' + evenArgs.coordinate.coordinates[1]);

            }
            else if(ESRI.ADF.Geometries.Point.isInstanceOfType(currentelement.get_geometry()) & currentelement._attributes["FeatureId"].startsWith("Stop")) 
            {
                __doPostBack("StopDrag", currentelement._attributes["FeatureId"] + "#" + evenArgs.coordinate.coordinates[0] + '#' + evenArgs.coordinate.coordinates[1]);

            }
            
        }
    //}
}
function drawGeometry(geometry, id) {
    map = $find(mapID);
    var highlightSymbol = null;
    var defaultSymbol = null;
    var graphicFeatureGroupID = null;

    // Initialize the graphic feature's symbol and graphicFeatureGroup ID based on the passed-in geometry type
    if (ESRI.ADF.Geometries.Point.isInstanceOfType(geometry)) {
        defaultSymbol = new ESRI.ADF.Graphics.MarkerSymbol(defaultImage, 16, 24, 'hand');
        // defaultSymbol.set_height(24);
        // defaultSymbol.set_width(32);

        highlightSymbol = new ESRI.ADF.Graphics.MarkerSymbol(hightlightImage, 16, 24, 'hand');
        // highlightSymbol.set_height(24);
        //highlightSymbol.set_width(35);

        graphicFeatureGroupID = "pointGraphics";
    }
    else if (ESRI.ADF.Geometries.Polyline.isInstanceOfType(geometry)) {
        defaultSymbol = new ESRI.ADF.Graphics.LineSymbol('blue', 3, 'hand');
        highlightSymbol = new ESRI.ADF.Graphics.LineSymbol('yellow', 3, 'hand');

        graphicFeatureGroupID = "lineGraphics";
    }
    else if (ESRI.ADF.Geometries.Polygon.isInstanceOfType(geometry)) {
        defaultSymbol = new ESRI.ADF.Graphics.FillSymbol('white', 'red', 3, 'hand');
        defaultSymbol.set_opacity(.5);

        highlightSymbol = new ESRI.ADF.Graphics.FillSymbol('yellow', '#00ffff', 3, 'hand');
        highlightSymbol.set_opacity(.5);

        graphicFeatureGroupID = "polygonGraphics";
    }
    var attributes = { "valueInTextbox": "test", "FeatureId": id }
    // Try retrieving the graphicFeatureGroup (i.e. layer) with the ID corresponding to the current 
    // geometry type.  If the group is not found, create it.
    var graphicFeatureGroup = $find(graphicFeatureGroupID);

    if (!graphicFeatureGroup) {
        // Create map tips to associate with the graphic features
        var mapTips = new ESRI.ADF.UI.MapTips();

        // Set the hover template, which will show as the title of the mapTips
        mapTips.set_hoverTemplate("<b><nobr>Dynamic Map Tip</nobr></b>");
        // Set the content template, which will show when the mapTip is clicked. When the mapTip is
        // rendered, (@valueInTextbox} will be replaced by the value of the corresponding graphicFeature's
        // "valueInTextbox" attribute, which is actually a property of the same name on the object stored
        // in the graphicFeature's attributes property.
        mapTips.set_contentTemplate('<span>Value in text box: <b>{@valueInTextbox}</b></span>')
        mapTips.set_animate(true);
        mapTips.set_maxheight(200);
        mapTips.set_width(null);

        // Create the graphic feature group with the ID, symbols, and mapTips.  Also, wire the
        // onMouseOverGraphics and onMouseOutGraphics to the group's mouseOver and mouseOut events    
        graphicFeatureGroup = $create(ESRI.ADF.Graphics.GraphicFeatureGroup, { "id": graphicFeatureGroupID,
            "symbol": defaultSymbol, "highlightSymbol": highlightSymbol
            //, "mapTips": mapTips
        },
             { "mouseOver": onMouseOverGraphics, "mouseOut": onMouseOutGraphics });

        // Add the new graphic feature group to the map
        map.addGraphic(graphicFeatureGroup);
        // mapTips.get_callout().show();
    }

    // Get the text from the textbox
    //var textInputValue = $get('textInput').value;
    // Initialize a JavaScript object with a property called "valueInTextbox" that has
    // the value retrieved from the textbox

    // Increment the graphicCount variable, which will be used in creating the graphicFeature's ID
    graphicCount += 1;
    // Create the graphic feature with a unique ID made up of the graphicFeatureGroupID and the graphicCount; 
    // the passed-in geometry; and the attributes object that specifies the valueInTextbox attribute
    var graphicFeature = $create(ESRI.ADF.Graphics.GraphicFeature, { "id": graphicFeatureGroupID + "_" + graphicCount,
        "geometry": geometry, "attributes": attributes
    });

    // Add the graphic to the group
    graphicFeatureGroup.add(graphicFeature);
}



Thanks
Lala Rabari
0 Kudos
BjørnSandvik
New Contributor
Hi Derek,

I tried your example, but I'm not able to move the marker after it's been hidden (by panning the map). Do you know how to fix it?

Bjørn


There's an easier way to do this. I think the code below was originally posted in the old forums but I've hung on to it for a while:
<!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>Moving a marker</title> 
    
    <link rel="stylesheet" type="text/css" href="http://serverapi.arcgisonline.com/jsapi/arcgis/2.2/js/dojo/dijit/themes/tundra/tundra.css"> 
    <script type="text/javascript" src="http://serverapi.arcgisonline.com/jsapi/arcgis/?v=2.2"></script> 
    
    <script type="text/javascript"> 
      dojo.require("esri.map");
      dojo.require("dojox.gfx.move");
 
      dojo.addOnLoad(init);
 
      var map;
      
      function init() {
        map = new esri.Map("map");
        dojo.connect(map, "onLoad", onMapLoad);
        
        var tiledMapServiceLayer = new esri.layers.ArcGISTiledMapServiceLayer("http://server.arcgisonline.com/ArcGIS/rest/services/ESRI_Imagery_World_2D/MapServer");
        map.addLayer(tiledMapServiceLayer);
      }
      
      function onMapLoad() {
        var geometry = map.extent.getCenter().offset(0, 15);
        var symbol = new esri.symbol.SimpleMarkerSymbol().setColor("red");
        var graphic = new esri.Graphic(geometry, symbol);
        
        // Add a graphic
        map.graphics.add(graphic);
 
        // Make the shape moveable
        var dojoShape = graphic.getDojoShape();
        var moveable = new dojox.gfx.Moveable(dojoShape);
        
        // Update the geometry at the end of move
        var moveStopToken = dojo.connect(moveable, "onMoveStop", function(mover) {
          // Get the transformation that was applied to 
          // the shape since the last move
          var tx = dojoShape.getTransform();
          
          var startPoint = graphic.geometry;
          var endPoint = map.toMap(map.toScreen(startPoint).offset(tx.dx, tx.dy));
          
          // clear out the transformation
          dojoShape.setTransform(null);
          
          // update the graphic geometry
          graphic.setGeometry(endPoint);
          
          // You can find quite a bit of information about
          // applying transformations to Dojo gfx shapes in this
          // document:
          // http://docs.dojocampus.org/dojox/gfx#coordinates-and-transformations
        });
      }
    </script> 
 
  </head> 
  <body class="tundra"> 
    <p> 
    </p> 
 
    <div id="map" style="width:700px; height:500px; border:1px solid #000;"></div> 
  </body> 
</html>
0 Kudos