none
Adding event to shapes drawn on map using drawing manager RRS feed

  • Question

  • Hi, 

    I want to bind the "click event" to shapes which we draw using Drawing Manager for Bing Map V8 like pushpins event.

    I am unable to do.

    Please guide for the same

    Please guide for the same

    Friday, April 28, 2017 1:37 PM

Answers

All replies

  • What you can do is move the shapes between the drawing manager and a layer. When editing the shapes, have them in the drawing manager and when done drawing/editing move them to a separate layer. From there you can add events to the layer and that will save you having to add/remove the events as you move them in and out of editing mode. Here is a code sample that shows how to mode the shape between the drawing manager and a layer:

    https://github.com/Microsoft/BingMapsV8CodeSamples/blob/master/Samples/Drawing%20Tools/DrawingTools_TogglePolygonEdit.html

    Here is a code sample on using events on layers:

    https://github.com/Microsoft/BingMapsV8CodeSamples/blob/master/Samples/Layers/View%20Shape%20Metadata.html


    [Blog] [twitter] [LinkedIn]

    Saturday, April 29, 2017 4:10 AM
  • Hi Ricky,

    We have similar kind of requirment. We want to add the click event on drawing shape. 

    We have chkecked above link but it did not fullfil our requirment. We want to add click event of shape draw by user using drawing tool. 

    Can you have sample where you achieve this or have any solution for it.

    Thanks! 


    Balasaheb

    Thursday, May 4, 2017 11:38 AM
  • Thursday, May 4, 2017 4:10 PM
  • Hi,

    Thanks for your reply. One more thing we need to ask, is there any way to identify when edit buton is clicked    because we want to swich the shape in edit mode when user clicked on edit button.

    Thanks! 


    Balasaheb

    Friday, May 5, 2017 10:54 AM
  • Fairly minor change. I've updated the sample to show this.

    [Blog] [twitter] [LinkedIn]

    Friday, May 5, 2017 4:10 PM
  • Hi Ricky,

    Thanks for your reply. We have checked and it is working for single shape but when we draw more one shape then edit and erase only work for recently draw shape not for others. For example when we draw two shape then edit only works for last shape that we draw not for first one.

    Can you let us know how to resolve this issue.

    Thansk!


    Balasaheb

    Tuesday, May 9, 2017 9:19 AM
  • I've just tried it and it works for all shapes on the map. If you select a shape to edit and go into edit mode, clicking another shape won't put it into edit mode, nor would it normally. You have to exist edit mode of your current shape being edited and then press the edit button again to edit the second shape. 

    [Blog] [twitter] [LinkedIn]

    Tuesday, May 9, 2017 4:11 PM
  • Hi Ricky,

    Thanks for your reply. We have checked and found that this issue was occured because of our other code. So we have resolve this issue now we are able to edit multiple shapes.

    Thanks!


    Balasaheb

    Wednesday, May 10, 2017 6:03 AM
  • Hi Ricky,

    I have one question after the shape is drawn how to get the SouthWest and NorthEast lat-long value of the shape on click event.

    I want the lat-long value of shape on click.

    Microsoft.Maps.Events.addHandler(baseLayer, 'click', function (e) {

    var sw = baseLayer.getBounds().getSouthWest();

    }

    I tried above code but it is not working. Please help how can i get the lat long values.

    Wednesday, June 7, 2017 12:38 PM
  • For the shape you would need to get it's coordinates and then calculate a LocationRect. For example:

    Microsoft.Maps.Events.addHandler(baseLayer, 'click', function (e) {
    	var shape = e.target;
    	var sw, ne;
    
    	if(shape instanceof Microsoft.Maps.Pushpin){
    		sw = shape.getLocation(); 
    		ne = sw;
    	} else {
    		var bounds = Microsoft.Maps.LocationRect.fromLocations(shape.getLocations());
    		sw = new Microsoft.Maps.Location(bounds.getSouth(), bounds.getWest());
    		ne = new Microsoft.Maps.Location(bounds.getNorth(), bounds.getEast());
    	}
    
    	//Do something with the sw and ne.	
    }

    Documentation on the LocationRect class can be found here: https://msdn.microsoft.com/en-us/library/mt712644.aspx

    We do have a LocationRect.fromShapes function planned which would simplify the above code.


    [Blog] [twitter] [LinkedIn]

    Thursday, June 8, 2017 1:50 AM
  • HI Ricky,

    Thanks for early response, Yes its working and i am able to get the SW and NE lat-long value of the shape.

    Bu there is one issue i facing right now : After drawing the shape on Map, When we get the southwest and northeast lat-long values

    i am rounding-over the lat-long value and appending to input-field and again sending for location request.

    When the new request triggered with round-over lat-long values, i can observe that there is an overlap on the shape however exception is shape should not change as both values are same.

    Please help to resolve the issue..

    I am not able to add screenshot, 

    Please refer below my code :

    function initMap() {
        map = new Microsoft.Maps.Map(document.getElementById('myMap'), {
            credentials: BING_MAPS_KEY
        });
    	
        
        infobox = new Microsoft.Maps.Infobox(map.getCenter(), {
            
            width: 800,
            height: 800,
            visible: false
        });
    
        
        infobox.setMap(map);
    												
        
        var table = document.getElementById("list");
        
        addTableRow(table, "Time", "SW", "NE", "#");
      
      
        var bingLocationRect = getBingBounds([$('#snap_BBSW').val(), $('#snap_BBNE').val()]);
        
        boundingBox = bingLocationRect;
    	//------------------------------------------------------------------
    		  Microsoft.Maps.loadModule('Microsoft.Maps.DrawingTools', function () {
                //Create a base layer to add drawn shapes.
                baseLayer = new Microsoft.Maps.Layer();
                //Add a click event to the base layer.
                Microsoft.Maps.Events.addHandler(baseLayer, 'click', function (e) {
    				
        
    				console.log("clicked");
    				var shape = e.target;
    				var sw, ne;
    
    				if(shape instanceof Microsoft.Maps.Pushpin){
    				sw = shape.getLocation(); 
    				ne = sw;
    				} else {
    				var bounds = Microsoft.Maps.LocationRect.fromLocations(shape.getLocations());
    				//sw = new Microsoft.Maps.Location(bounds.getSouth(), bounds.getWest());
    				//ne = new Microsoft.Maps.Location(bounds.getNorth(), bounds.getEast());
    				//console.log(sw+""+ne);
    				var swlat = bounds.getSouth();
    				var swlon = bounds.getWest();
    				var neLat = bounds.getNorth();
    				var neLon = bounds.getEast();
    				var BBSW = swlat.toFixed(6) + ", " + swlon.toFixed(6);
    				var BBNE = neLat.toFixed(6) + ", " + neLon.toFixed(6);
    				//console.log("value2");
    				console.log(BBSW+"---"+BBNE);
    				document.getElementById("snap_BBSW").value = BBSW;
    				document.getElementById("snap_BBNE").value = BBNE;
    				}
    				
    				
    				});
    				map.layers.insert(baseLayer);
    				
    			
                
                //Create an instance of the DrawingTools class and bind it to the map.
                var tools = new Microsoft.Maps.DrawingTools(map);
                //Show the drawing toolbar and enable editting on the map.
                tools.showDrawingManager(function (manager) {
                    drawingManager = manager;
                    Microsoft.Maps.Events.addHandler(drawingManager, 'drawingEnded', function (e) {
                        //When use finisihes drawing a shape, removing it from the drawing layer and add it to the base layer.
                        moveShapesBetweenLayers(drawingManager, baseLayer);
                    });
                    Microsoft.Maps.Events.addHandler(drawingManager, 'drawingModeChanged', function (e) {
                        //When the mode changes to edit or erase, move all shapes in the baseLayer to the drawing layer.
                        if (e === Microsoft.Maps.DrawingTools.DrawingMode.edit || e === Microsoft.Maps.DrawingTools.DrawingMode.erase) {
                            moveShapesBetweenLayers(baseLayer, drawingManager);
                        }
                    });
                })
            });
    				
    
    }
    function moveShapesBetweenLayers(fromLayer, toLayer) {
            var shapes = fromLayer.getPrimitives();
            if (shapes) {
                fromLayer.clear();
                toLayer.add(shapes);
    			
            }
    }

    Thanks in advance..!!!

    Regards

    Amaresh


    • Edited by mantuamaresh Thursday, June 8, 2017 10:07 AM modified
    Thursday, June 8, 2017 10:01 AM
  • Can you go into more detail about what you mean by "i can observe that there is an overlap on the shape however exception is shape should not change as both values are same". I don't understand what you are saying here.

    [Blog] [twitter] [LinkedIn]

    Friday, June 9, 2017 6:52 AM
  • Hi Ricky,

    I mean After drawing the shape on Map, When we get the southwest and northeast lat-long values with the latlong values again i am sending location request for the rectangle/shape so i can see all overlays inside the bounding box.

    But the problem is when the second time location request sent with the same lat-long values the shape/rectangle looks overlap on the first, there is an minor overlap of the two shapes although both the values are same.

    Lets simplify it little more to get clarity :

    (We have an internal tool which will send request for all overlays when i provide the SW and NE lat long value in a bounding box/rectangle)

    - I draw a rectangle on map and got the coordinates of my rectangle and my rectangle is present on my map

    - Now i am sending again location request with the obtained lat-long values 

    - New request will draw a rectangle with the lat-long values requested

    So expectation is as both the rectangle should be same and there should not be any overlap as the requested lat-long value is same for both.

    There is minor overlap observed for the rectangle.

    I tried to upload the screenshot which will help you to understand the problem but was not able to do so.

    If still query is not clear please send me your Email-id i will send the screenshot which will be easy for u to understand the problem.

    Thanks 

    Amaresh


    • Edited by mantuamaresh Friday, June 9, 2017 10:20 AM simplified query
    Friday, June 9, 2017 10:11 AM
  • Is the data returned which is being used to generate the bounding boxes the same? You aren't using map.getBounds to get or compare the bounding box right.

    [Blog] [twitter] [LinkedIn]

    Friday, June 9, 2017 4:23 PM
  • HI Ricky,

    Please see below function to get the bounding box : 

    There is one more problem with the function click event is not getting enabled , Please help.


    code:

    function getBingBounds(bounds) {
        var swLat, swLng, neLat, neLng;

        if (typeof (bounds[0]) !== 'undefined') {
            if (bounds.length == 4) {
                swLat = bounds[0];
                swLng = bounds[1];
                neLat = bounds[2];
                neLng = bounds[3];
            } else if (bounds.length == 2) {
                var sw = bounds[0].split(',');
                var ne = bounds[1].split(',');
                swLat = sw[0];
                swLng = sw[1];
                neLat = ne[0];
                neLng = ne[1];
            }
        }
        var locations = [
            new Microsoft.Maps.Location(swLat, swLng),
            new Microsoft.Maps.Location(neLat, neLng)
        ];

        return new Microsoft.Maps.LocationRect.fromLocations(locations);
    }

    function drawBingRectangle(bingBounds) {
        var polygon = new Microsoft.Maps.Polygon([
            new Microsoft.Maps.Location(bingBounds.bounds[0], bingBounds.bounds[3]), //upper Left
            new Microsoft.Maps.Location(bingBounds.bounds[0], bingBounds.bounds[1]), //lower Left
            new Microsoft.Maps.Location(bingBounds.bounds[2], bingBounds.bounds[1]), //lower right
            new Microsoft.Maps.Location(bingBounds.bounds[2], bingBounds.bounds[3])], { fillColor: new Microsoft.Maps.Color(10, 51, 204, 51) }); // upper right
        map.entities.push(polygon);

    }

    function showSnapData(bounds, timestamp, editable, request, response, header) {

        var swLat, swLng, neLat, neLng;
        var bingBounds = getBingBounds(bounds);

        if (typeof (bingBounds) !== 'undefined') {
            drawBingRectangle(bingBounds);

            bingRect = new Microsoft.Maps.Polygon([
                new Microsoft.Maps.Location(bingBounds.bounds[0], bingBounds.bounds[3]), //upper Left
                new Microsoft.Maps.Location(bingBounds.bounds[0], bingBounds.bounds[1]), //lower Left
                new Microsoft.Maps.Location(bingBounds.bounds[2], bingBounds.bounds[1]), //lower right
                new Microsoft.Maps.Location(bingBounds.bounds[2], bingBounds.bounds[3])], null); // upper right
        }

        var rect = {
            rect: bingRect,
            header: header,
            request: request,
            response: response,
            id: snapData.length,
            timestamp: new Date(timestamp),
            inputBoundSW: document.createElement("input"),
            inputBoundNE: document.createElement("input"),
            inputChange: function () {
                /*  var sw = rect.inputBoundSW.value.split(',');
                  var ne = rect.inputBoundNE.value.split(',');
                  var bounds = new google.maps.LatLngBounds(
                  new google.maps.LatLng(sw[0],sw[1]),
                  new google.maps.LatLng(ne[0],ne[1])
                  );
                  rect.rect.setBounds(bounds);*/
            },
          
            boundsChanged: function () {
                rect.inputBoundSW.value = (rect.rect.geometry.bounds[0].toFixed(6) + ", " + rect.rect.geometry.bounds[1].toFixed(6));
                rect.inputBoundNE.value = (rect.rect.geometry.bounds[2].toFixed(6) + ", " + rect.rect.geometry.bounds[3].toFixed(6));

                
            }
        };

        rect.inputBoundSW.onchange = function () {
            rect.inputChange.call(rect);
        }
            ;

        rect.inputBoundNE.onchange = function () {
            rect.inputChange.call(rect);
        }
            ;

        if (typeof (rect.request) !== 'undefined') {
            var doc = $.parseXML(rect.request.payload);
            rect.$request = $(doc);
        }

        if (typeof (rect.response) !== 'undefined') {
            var doc = $.parseXML(rect.response);
            rect.$response = $(doc);
            rect.$overlays = rect.$response.find("navigation overlays-response > overlay");
            if (rect.$overlays.length == 0) {
                rect.$overlays = rect.$response.find("navigation places-response > place");
            }
            rect.boundsChanged.call(rect);
        }
    Microsoft.Maps.Events.addHandler(bingRect, 'click', function (e) {
    console.log("clicked3");
    var swLat, swLng, neLat, neLng;
    var inputBoundSW;
    var inputBoundNE; 
    var sw = rect.inputBoundSW.value.split(',');
                var ne = rect.inputBoundNE.value.split(',');
                var bounds = new google.maps.LatLngBounds(
                new google.maps.LatLng(sw[0],sw[1]),
                new google.maps.LatLng(ne[0],ne[1])

    );
    console.log(sw+"--"+ne);
    if(sw == rect.inputBoundSW.value && ne == rect.inputBoundNE.value)
    {

    tableLine.css("background", "#FF8888");

    }else{

    tableLine.css("background", "");
    }
            });
    Microsoft.Maps.Events.addHandler(bingRect, 'mouseout', function (e) {
    console.log("clicked5");
    var swLat, swLng, neLat, neLng;
    var inputBoundSW;
    var inputBoundNE; 
    var sw = rect.inputBoundSW.value.split(',');
                var ne = rect.inputBoundNE.value.split(',');
                var bounds = new google.maps.LatLngBounds(
                new google.maps.LatLng(sw[0],sw[1]),
                new google.maps.LatLng(ne[0],ne[1])
    );


    tableLine.css("background", "");

    //}
    });


        if (typeof (rect.rect) !== 'undefined') {
           
        }

        
    }

    Regards

    Amaresh


    • Edited by mantuamaresh Friday, June 9, 2017 4:53 PM modified
    Friday, June 9, 2017 4:51 PM
  • My requirement id i have to draw a rectangle either by using Drawing tool or have to give user option to draw using shift and right click.

    Once rectangle is drawn on click i should get the southwest and northeast bound.

    After getting the bounds again send new request with the received lat long value on same bounding box to see the no of overlays.

    Regards

    Amaresh

    Friday, June 9, 2017 4:56 PM
  • Ok, the second call to LocationRect.fromLocations is likely the issue as it goes through a lot of different calculations and is meant to encompass the locations and likely adds a slight buffer to account for floating point error. It also looks like your bound information might be a string at some point, make sure to convert this to a float. This could be part of the issue as well. Here is a modified version of your function to try:

    function getBingBounds(bounds) {
        var swLat, swLng, neLat, neLng;
    
        if (typeof (bounds[0]) !== 'undefined') {
            if (bounds.length == 4) {
                swLat = parseFloat(bounds[0]);
                swLng = parseFloat(bounds[1]);
                neLat = parseFloat(bounds[2]);
                neLng = parseFloat(bounds[3]);
            } else if (bounds.length == 2) {
                var sw = bounds[0].split(',');
                var ne = bounds[1].split(',');
                swLat = parseFloat(sw[0]);
                swLng = parseFloat(sw[1]);
                neLat = parseFloat(ne[0]);
                neLng = parseFloat(ne[1]);
            }
        }
    
    	var center = new Microsoft.Maps.Location((neLat + swLat)/2, (swLng + neLng)/2);
    	var height = neLat - swLat;
    	var width = neLng - swLng;
    
        return new Microsoft.Maps.LocationRect(center, width, height);
    }


    [Blog] [twitter] [LinkedIn]

    Friday, June 9, 2017 5:42 PM
  • Hi Ricky,

    I tried with the modified code, but i am facing the same issue. overlap observed. please help.

    Regards

    Amaresh


    • Edited by mantuamaresh Friday, June 9, 2017 6:34 PM modified
    Friday, June 9, 2017 6:32 PM
  • Can you provide the info for the location text originally calculated and then the bounding information your service returns later.

    [Blog] [twitter] [LinkedIn]

    Friday, June 9, 2017 8:23 PM
  • Hi Ricky,

    As you know currently we are first drawing a rectangle/shape on map and than on click receiving the SW and NE lat long value and the same Lat-long value i am setting up in text field to send new request.

    The only problem what i feel is when we draw a rectangle using drawing tool on map the rectangle size is not completely square however when new new request is send through service with lat long value its drawing a polygon. that is where the problem lies little overlap is happening if drawn rectangle is not completely square.

    On click drawn shape i am receiving below lat long value :

    12.888133, 77.488365---12.996544, 77.669640

    and when service is run its printing below lat long value :

    on function 12.888133,77.488365,12.996544,77.66964

    For google maps i am giving user an option to create a bonding box by shift+right click and drag so exact rectangle is getting created with no overlap

    If we can achieve something like that than overlap issue will not be there.

    I mean is there any way i can give user an option to shift and drag to create a rectangle than get the lat-long value.

    Below code for polygon in Bing maps :

    function drawBingRectangle(bingBounds) {
    	console.log(bingBounds);
        var polygon = new Microsoft.Maps.Polygon([
            new Microsoft.Maps.Location(bingBounds.bounds[0], bingBounds.bounds[3]), //upper Left
            new Microsoft.Maps.Location(bingBounds.bounds[0], bingBounds.bounds[1]), //lower Left
            new Microsoft.Maps.Location(bingBounds.bounds[2], bingBounds.bounds[1]), //lower right
            new Microsoft.Maps.Location(bingBounds.bounds[2], bingBounds.bounds[3])], { fillColor: new Microsoft.Maps.Color(10, 51, 204, 51) }); // upper right
        map.entities.push(polygon);
    
    }

    Please see below google map code for reference :

    function initMap() {
    	
    	//Google = document.getElementById('Google');
    	
    	//Google.onclick = function() {
    		
    	map = new google.maps.Map(document.getElementById('map'),{
            center: {
                lat: 48.774182,
                lng: 9.169925
            },
            zoom: 13
    			
        });
    	
        infoWindow = new google.maps.InfoWindow({
           content: "holding..."
    	   
    	   
        });
    	
    	
    	google.maps.event.addListenerOnce(map, 'idle', function() {
           google.maps.event.trigger(map, 'resize');
        });
       // $('#map').show();
    	//$('#myMap').hide();
        //var table = $("#list");
        var table = document.getElementById("list");
        //addTableRow(table,document.createTextNode("Time"),document.createTextNode("SW"),document.createTextNode("SW"));
        addTableRow(table, "Time", "SW", "NE", "#");
        
        //var date = new Date();
        //$("#time_from").val(Date.now());
        //$('#datetimepicker1').datetimepicker();
    	
        var googleBounds = getGoogleBounds([$('#snap_BBSW').val(), $('#snap_BBNE').val()]);
        boundingBox = new google.maps.Rectangle({
            bounds: googleBounds,
            strokeColor: '#0000FF',
            fillColor: '#0000FF',
            fillOpacity: 0.1,
            editable: true,
            draggable: true
    		
        }); 
    	//var counter;	
        boundingBox.addListener('bounds_changed', function() {
            var ne = boundingBox.getBounds().getNorthEast();
            var sw = boundingBox.getBounds().getSouthWest();
            $('#snap_BBSW').val(sw.lat().toFixed(6) + ", " + sw.lng().toFixed(6));
            $('#snap_BBNE').val(ne.lat().toFixed(6) + ", " + ne.lng().toFixed(6));
    		//counter++;
    		console.log("Bounds changes-1");
            //$('#snap_BBSW').val()
    		
        }); 
    	
        showBoundingBox($('#snap_showBBCheckBox').get(0).checked);
    	
    	var shiftdown = false;
    	var gribBoundingBox = null;
    	var boxcomplete = false;
    
    	$(window).keydown(function (evt) {
    		if (evt.which === 16) { // shift
    			shiftdown = true;
    		}
    	}).keyup(function (evt) {
    		if (evt.which === 16) { // shift
    			shiftdown = false;
    		}
    	});
    
    	function cleargribBoundingBox(){
    		if(gribBoundingBox !== null){
    			gribBoundingBox.setMap(null); // remove the rectangle
    		}
    		boxcomplete = false;
    	}
    	google.maps.event.addListener(map, 'mousedown', function (e) {
    		if (shiftdown) {
    			map.setOptions({
    				draggable: false
    			});
    			cleargribBoundingBox();
    			gribBoundingBox = new google.maps.Rectangle({
    				map: map,
    				bounds: new google.maps.LatLngBounds(e.latLng,e.latLng),
    				fillOpacity: 0.15,
    				strokeWeight: 0.9,
    				clickable: false
    			});
    		}
    	});
    	google.maps.event.addListener(map, 'mousemove', function (e) {
    		if(gribBoundingBox !== null){
    			if(!boxcomplete){
    				//moving mouse accross map, box is in process of being drawn
    				//lets update its bounds
    				var boxvalue = gribBoundingBox.setBounds(gribBoundingBox.getBounds().extend(e.latLng));
    			} else{
    				//moving mouse accross map, box is present
    			}
    		} else {
    			//moving mouse over map, no bounding box present
    			//either no bounding box has been made yet or we are not holding shift and we are just dragging the map around
    		}
    		
    	});
    	google.maps.event.addListener(map, 'click', function (e) {
    		if(gribBoundingBox !== null){ //we just completed a box
    			boxcomplete = true;
    			var sw = gribBoundingBox.getBounds().getSouthWest();
    			var ne = gribBoundingBox.getBounds().getNorthEast();
                SWL = (sw.lat().toFixed(6) + ", " + sw.lng().toFixed(6));
                NEL = (ne.lat().toFixed(6) + ", " + ne.lng().toFixed(6));
    			document.getElementById("snap_BBSW").value = SWL;
    			document.getElementById("snap_BBNE").value = NEL;
    			map.setOptions({
    				draggable: true
    			});
    		}
    	}); 
    	 
    }
    

    Let me know if you need any further info..

    Thanks for your support..

    Regards

    Amaresh


    • Edited by mantuamaresh Saturday, June 10, 2017 5:13 PM Modified
    Saturday, June 10, 2017 5:12 PM
  • ok, so the issue isn't with the bounding box calculations but that your drawn rectangle isn't perfectly even. Instead of using the drawing tools to try and draw a rectangle you can create a custom drawing function for this. Alternatively, take a look at this sample which adds support for circles and rectangles. http://bingmapsv8samples.azurewebsites.net/#DrawingTools_CustomToolbar

    [Blog] [twitter] [LinkedIn]

    Saturday, June 10, 2017 5:42 PM
  • Hi Ricky,

    Thanks for the info. I tried below code from the link and now i am able to draw a rectangle but i am not getting how to get the rectangle Southwest and Northeast Lat-Long value.

    Please help and let me know how can i simplify the code.

    Below code is not working :

    var tools;
        var drawingLayer;
        var currentShape;
        var currentMode;
        var events = [];
        var style = {
            color: 'purple',
            fillColor: 'rgba(0,255,0,0.5)',
            strokeColor: 'blue',
            strokeThickness: 3
        };
    function initMap() {
        map = new Microsoft.Maps.Map(document.getElementById('myMap'), {
            credentials: BING_MAPS_KEY
        });
    	
        
        infobox = new Microsoft.Maps.Infobox(map.getCenter(), {
            
            width: 800,
            height: 800,
            visible: false
        });
    
        
        infobox.setMap(map);
    												
        
        var table = document.getElementById("list");
        
        addTableRow(table, "Time", "SW", "NE", "#");
      
      
        var bingLocationRect = getBingBounds([$('#snap_BBSW').val(), $('#snap_BBNE').val()]);
        
        boundingBox = bingLocationRect;
    	//--------------------------------
    	Microsoft.Maps.loadModule(['Microsoft.Maps.DrawingTools', 'Microsoft.Maps.SpatialMath'], function () {
                //Create a layer for the drawn shapes.
                drawingLayer = new Microsoft.Maps.Layer();
                map.layers.insert(drawingLayer);
                //Create an instance of the DrawingTools class and bind it to the map.
                tools = new Microsoft.Maps.DrawingTools(map);
            });
            //When the user presses 'esc', take the polygon out of edit mode and re-add to base map.
            document.getElementById('myMap').onkeypress = function (e) {
                if (e.charCode === 27) {
                    setMode(null);
                }
            };
    		
    
    	
    }
    function setDrawingMode(mode, elm) {
            clearSelection('DrawingModes', 'editButton');
            elm.className = 'selectedEditButton';
            switch (mode) {
                case 'pushpin':
                    drawPushpin();
                    break;
                case 'polyline':
                    drawPolyline();
                    break;
                case 'polygon':
                    drawPolygon();
                    break;
                case 'circle':
                    drawCircle();
                    break;
                case 'rectangle':
                    drawRectangle();
                    break;
                case 'edit':
                    edit();
                    break;
                case 'erase':
                    erase();
                    break;
                default:
                    break;
            }
        }
    
    	function drawRectangle() {
            if (setMode('rectangle')) {
                var isMouseDown = false;
                events.push(Microsoft.Maps.Events.addHandler(map, 'mousedown', function (e) {
                    //Lock map so it doesn't move when dragging.
                    map.setOptions({ disablePanning: true });
                    //Create a polygon for the circle.
                    currentShape = new Microsoft.Maps.Polygon([e.location, e.location, e.location], style);
                    //Store the center point in the polygons metadata.
                    currentShape.metadata = {
                        type: 'rectangle'
                    };
                    drawingLayer.add(currentShape);
                    isMouseDown = true;
    				Microsoft.Maps.Events.addHandler(currentShape, 'click', function (e) {
                //Remove the polygon from the map as the drawing tools will display it in the drawing layer.
    			console.log("clicked");
                var swlat = map.getBounds().getSouth();
    			var swlon = map.getBounds().getWest();
    			var neLat = map.getBounds().getNorth();
    			var neLon = map.getBounds().getEast();
    			//var sw = gribBoundingBox.getBounds().getSouthWest();
    			var BBSW = swlat.toFixed(6) + ", " + swlon.toFixed(6);
    			var BBNE = neLat.toFixed(6) + ", " + neLon.toFixed(6);
    			console.log("value2");
    			console.log(BBSW+"---"+BBNE);
    			document.getElementById("snap_BBSW").value = BBSW;
    			document.getElementById("snap_BBNE").value = BBNE;
              
    			});
                }));
                events.push(Microsoft.Maps.Events.addHandler(map, 'mousemove', function (e) {
                    if (isMouseDown) {
                        updateRectangle(e);
                    }
                }));
                events.push(Microsoft.Maps.Events.addHandler(map, 'mouseup', function (e) {
                    updateRectangle(e);
                    //Unlock map panning.
                    map.setOptions({ disablePanning: false });
                    isMouseDown = false;
                }));
    			 
            }
        }
    	function updateRectangle(e, firstCornerIdx) {
            if (typeof firstCornerIdx === 'undefined') {
                firstCornerIdx = 2;
            }
            if (currentShape && currentShape.metadata && currentShape.metadata.type === 'rectangle') {
                //Get the first corner of the rectangle.
                var locs = currentShape.getLocations();
                var secondIdx = (firstCornerIdx + 1) % 4;
                var thirdCornerIdx = (firstCornerIdx + 2) % 4;
                var fourthCornerIdx = (firstCornerIdx + 3) % 4;
                //Update the opposite corner of the rectangle.
                locs[firstCornerIdx] = e.location;
                //Calculate the other 3 corners of the rectanle.
                locs[secondIdx] = new Microsoft.Maps.Location(locs[thirdCornerIdx].latitude, locs[firstCornerIdx].longitude);
                locs[fourthCornerIdx] = new Microsoft.Maps.Location(locs[firstCornerIdx].latitude, locs[thirdCornerIdx].longitude);
                if (locs.length == 5) {
                    locs[4] = locs[0];
                }
                currentShape.setLocations(locs);
            }
        }
    	function setMode(mode) {
            //Remove all attached events.
            for(var i=0; i < events.length;i++){
                Microsoft.Maps.Events.removeHandler(events[i]);
            }
            events = [];
            //Unlock map so incase it has been locked previously.
            map.setOptions({ disablePanning: true });
            var state = false;
            if (currentMode === mode || mode == null) {
                //Toggle out of currentMode mode.
                currentMode = null;
                clearSelection('DrawingModes', 'editButton');
            } else {
                currentMode = mode;
                state = true;
            }
            resetDrawingState();
            return state;
        }
    	function resetDrawingState() {
            //Stop any current drawing.
            if (currentShape) {
                tools.finish(function (s) {
                    //Add the completed shape to the drawning to the drawing layer.
                    drawingLayer.add(s);
                });
                currentShape = null;
            }
            if(currentMode !== 'edit') {
                //Disable pushpin dragging in layer.
                setPushpinDraggability(false);
            }
        }
        function setPushpinDraggability(draggable) {
            var shapes = drawingLayer.getPrimitives();
            for (var i = 0, len = shapes.length; i < len; i++) {
                if (shapes[i] instanceof Microsoft.Maps.Pushpin) {
                    shapes[i].setOptions({ draggable: draggable });
                }
            }
        }
    	function clearSelection(parentId, className) {
            var parent = document.getElementById(parentId);
            for (var i = 0; i < parent.children.length; i++) {
                parent.children[i].className = className;
            }
        }

    Regards

    Amaresh

    Sunday, June 11, 2017 8:37 AM
  • Its working now, I am able to fetch the lat long values from 

     var locs = currentShape.getLocations();

    Thanks for your support..

    Regards

    Amaresh

    Monday, June 12, 2017 10:27 AM
  • Hi Ricky,

    We have one question on this.

    We used above code to switch between layers and it is working fine. but when we tried to draw overlap shape as we do it using drawing manager. We are not able to draw overlap shape. Can you please let us know how to achieve this.


    Balasaheb



    Wednesday, June 14, 2017 2:29 PM