perliedman / leaflet-routing-machine

Control for routing in Leaflet
https://www.liedman.net/leaflet-routing-machine/
Other
1.06k stars 347 forks source link

Custom Marker makes routes undefined #629

Open shinmothy opened 3 years ago

shinmothy commented 3 years ago

Hi, I currently have an issue where I put in custom markers in a route control, it gives me an error in my osrmv1 route, which happened before.

`function onLocationFound(e) { console.log(e); L.marker([e.latitude, e.longitude], { icon: home_icon }).bindPopup("You are here!").addTo(m); $.get('vac_sites.csv', function (csvString) {

let data = Papa.parse(csvString, { header: true, dynamicTyping: true }).data;
console.log(data)

data.pop()
console.log(data)
let counter = 0;
for (let i = 1; i < data.length; i++) {
  let row = data[i];
  let myRouter = L.Routing.osrmv1({
    serviceUrl: 'https://xxx.xxx.xxx:443/route/v1'
  });
  let self_loc = new L.Routing.Waypoint;
  self_loc.latLng = L.latLng([e.latitude, e.longitude]);
  let site_loc = new L.Routing.Waypoint;
  site_loc.latLng = L.latLng([row.Latitude, row.Longitude]);
  myRouter.route([self_loc, site_loc], function (err, routes) {
    distance = routes[0].summary.totalDistance;
    row.distance = distance
    console.log(row)
    counter += 1;
    console.log(counter);
    if (counter === data.length-1){    
      console.log("Nothing runs after the for loop");
      let best = data.reduce(function (prev, current) {
      return (prev.distance < current.distance) ? prev : current
        });
      console.log(best)
      console.log(best.Latitude)

      routeControl = L.Routing.control({
      router: myRouter,
      waypoints: [
        self_loc,
        L.latLng(best.Latitude, best.Longitude),
      ],
      createMarker: function(j, wp, nWps) {
          if (j === 0) {
              return L.marker(wp.latLng, {icon: home_icon}).bindPopup("You are here!");
          } else if (j === nWps -1){
              return L.marker(wp.latLng, {icon: vax_icon }).bindPopup(`<b>Facility Name:</b> ${row.Name}<br><b>Address:</b> ${row.Address}<br><b>Telephone:</b> ${row.Telephone}<br><b>Website:</b> ${row.Website}`);
          }
      },
      draggableWaypoints: false,
      routeWhileDragging: false,
      units: 'imperial',
      lineOptions : {
          addWaypoints: false 
        }
      }).addTo(m);
    }
  });
}

}); }`

The code works perfectly fine and my markers work and all, just the error is kinda annoying. Error: script.js:94 Uncaught TypeError: Cannot read property '0' of undefined at Function.<anonymous> (script.js:94) at i.<anonymous> (leaflet-routing-machine.js:18004) at XMLHttpRequest.loaded (leaflet-routing-machine.js:46) Which is the routes[0] part. When i take out createMarker, I don't get the error.