0

I am wanting to allow the user to be able to drag a map marker, in OpenLayers 3, but constrain the dragging to the lineString that represents the route. Based on the code example on Stack Exchange I am able to move the marker and have an onChange handler, as follows:

geoMarker.on('change',function() {
    var point = scope.getGeometry().getCoordinates();
    if ( scope.map.getLayer('routeLayer').getSource().getFeaturesAtCoordinate(point) == 0 ) {
        // TODO if point is not in lineString, then prevent drag
    } else {
        // TODO get index of nearest point in routeLine and display
        //      location information
    }
});

I looked at the OpenLayers 3 examples, but nothing jumped out as how to go about doing this.

1 Answer 1

1

Example taken from here : http://openlayers.org/en/v3.15.1/examples/igc.html

  var displaySnap = function(coordinate) {
    var closestFeature = vectorSource.getClosestFeatureToCoordinate(coordinate);
    var info = document.getElementById('info');
    if (closestFeature === null) {
      point = null;
      line = null;
      info.innerHTML = ' ';
    } else {
      var geometry = closestFeature.getGeometry();
      var closestPoint = geometry.getClosestPoint(coordinate);
      if (point === null) {
        point = new ol.geom.Point(closestPoint);
      } else {
        point.setCoordinates(closestPoint);
      }
      var date = new Date(closestPoint[2] * 1000);
      info.innerHTML =
          closestFeature.get('PLT') + ' (' + date.toUTCString() + ')';
      var coordinates = [coordinate, [closestPoint[0], closestPoint[1]]];
      if (line === null) {
        line = new ol.geom.LineString(coordinates);
      } else {
        line.setCoordinates(coordinates);
      }
    }
    map.render();
  };

  map.on('pointermove', function(evt) {
    if (evt.dragging) {
      return;
    }
    var coordinate = map.getEventCoordinate(evt.originalEvent);
    displaySnap(coordinate);
  });

  map.on('click', function(evt) {
    displaySnap(evt.coordinate);
  });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.