Thursday, 25 April 2019

openlayers - How to get the coordinates of the starting and ending points of a line in ol.interaction.Draw in OL3


I'm using Openlayers3 for drawing and storing lines, and then doing some processes on the inputs. Now I want to get the coordinates of the starting and ending points of the line while the line is being drawn. In other words, as the user clicks to start the line the coordinates of the starting point being collected and do some process. When the last point is inserted the same thing happens. I have read so many answers here mostly referring to OL2 and I also read the OL3 documents, but seems something is not right. Here is part of my code:


draw.on('drawstart', function(e1) {    
var mouseCoordinatesStart=map.getEventCoordinate(e1);
infoBox.innerHTML = 'you just started to draw at:
' + mouseCoordinatesStart;});


draw.on('drawend', function(e2) {//I have tried the same process as the drawstart but the results are the same. here I just want to show I tried different methods.
var mousePixel= map.getEventPixel(e2);
var mouseCoordinatesEnd=map.getCoordinateFromPixel(mousePixel);
infoBox.innerHTML = 'drawing endded at:
'+ mouseCoordinatesEnd;});

it seems that the function for handling the drawstart works for the first time but then the drawend event does not change the coordinates. However, if I zoom out or in then the coordinates change but then I guess it's not the coordinates of the endpoint of the line. Could someone help me with this issue?



Answer



why dont you get the feature drawn and then get the coordinates out of it. It should be much faster.


draw.on('drawend', function(e2) {
var feature = e2.feature;

var geometry = feature.getGeometry();

//depending on the type of geometry drawn you may get first and last
//coordinate. From your description I guess you draw a linestring
//you may clarify that using geometry.getType()
//so for ol.geom.LineString do as follows. According to the
//documentation this should work for any type of geometries
var startCoord = geometry.getFirstCoordinate();
var endCoord = geometry.getLastCoordinate();
//If you are not sure what the type is, or if you face any problems

//with getFirstCoordinate, getLastCoordinate
//you may go for a more general technique

var coordinates = geometry.getCoordinates();
//and then parse the coordinates object to get first and last
var startCoord = coordinates[0];
var endCoord = coordinates[coordinates.length-1];
});

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...