验证标记是否在路线内部

verify if marker is inside from route

我叫 João,我正在使用 leaflet.js 做我在巴西坎皮纳斯大学的结业课程项目。要解决的问题是:marker需要留在route里面,如果不是,需要return一个false。有人能帮我吗?谢谢

var map = L.map('map',18);

  L.tileLayer('https://{s}.tile.osm.org/{z}/{x}/{y}.png', {
    maxZoom: 20,
  }).addTo(map);

  var cont = 0;
  var marker = null;

  function refresh() {

    $.ajax({
      method: "GET",
      url: "mapa/coordenada",
      dataType: "json"
    })
      .done(function( msg ) {
        registro_coordenada(msg.coordenada);
      });
  }

  function select_cord() {

    $.ajax({
      method: "GET",
      url: "mapa/coordenada",
      dataType: "json"
    })
      .done(function( msg ) {
        add_cord(msg.coordenada);
      });
  }

  function add_cord(coordenada){
    out = coordenada.split(",");

    var control = L.Routing.control(L.extend(window.lrmConfig, {
      waypoints: [
      L.latLng(-22.5627235,-47.425501),
      L.latLng([out[0],out[1]])
  ],
      geocoder: L.Control.Geocoder.nominatim(),
      routeWhileDragging: true,
      reverseWaypoints: true,
      showAlternatives: true,
      altLineOptions: {
          styles: [
            {color: 'black', opacity: 0.15, weight: 9},
            {color: 'white', opacity: 0.8, weight: 6},
            {color: 'blue', opacity: 0.5, weight: 2}
        ]
    }
  })).addTo(map);

  L.Routing.errorControl(control).addTo(map);

  }

var icone = new L.Icon({
                      iconUrl: 'https://cdn.rawgit.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-red.png',
                      shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/images/marker-shadow.png',
                      iconSize: [25, 41],
                      iconAnchor: [12, 41],
                      popupAnchor: [1, -34],
                      shadowSize: [41, 41]
                    });


function registro_coordenada(coordenada){
  out = coordenada.split(",");
  if (cont === 0 ){
    marker = L.marker([out[0],out[1]], {icon: icone}).addTo(map).bindPopup("<b>Localização atual</b>").openPopup();
    cont = 1;
    return;
  }
  map.removeLayer(marker);
  //var marker = L.marker([out[0],out[1]]).remove(map).bindPopup("<b>Localização atual</b>").openPopup();
  marker = L.marker([out[0],out[1]], {icon: icone}).addTo(map).bindPopup("<b>Localização atual</b>").openPopup().closePopup();
}

$(document).ready(function(){
  if ($('#map')){
    self.setInterval(function () {
      refresh()
    }, 1000);
  }
  select_cord();
});

问题无法在GitHub

解决

如果有人帮助我,我将不胜感激!

你不能这样做,因为计算几何的工作原理有更精细的细节:因为 Linestring 的点以浮点表示,所以可能存在没有(有效)浮动的线段沿该段的点的点表示。

这里采用的方法是计算给定点到给定线串的距离,然后检查该距离是否在阈值内。所以"inside"的意思就变了,变成了"no more than (threshold) distance apart from the line".

请注意,由于浮点舍入误差(在那些在某些情况下,点到线的距离小于所使用的浮点格式的精度或计算过程中累积的浮点误差)。

点到线串距离算法最著名的(据我所知)javascript 实现是 the one in Turf.js