perliedman / leaflet-routing-machine

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

Unable to add second marker to map based on onClick in Map #613

Open antonioOrtiz opened 3 years ago

antonioOrtiz commented 3 years ago

Thanks for such a awesome Library! I realize this is a question and not a problem with the Library but could someone answer this question? I'd appreciate it!

I have a map where I'd like to add two point a starting and ending to get a route!

In the Map component I have an addMarker function which is getting the latitude and longitude from the event object when a user clicks. I take that info and pass that to the routing machine.

In my Routing Machine component, in the L.Routing.control object i've set the waypoints to null but later I use the setWaypoints method available to set the 'latLng' I am getting from addMarker.

Also I use the createMarker prop to pass some logic to change the default colors.

I have some logs in the Routing Machine, but they only log for the first Marker, afterwards I don't get anything.

This is my Map:

import React, { useState, useEffect } from 'react'
import { Map } from 'react-leaflet';
import LocateControl from '../LocateControl/LocateControl.jsx';
import MapboxLayer from '../MapboxLayer/MapboxLayer.jsx';
import Routing from '../RoutingMachine/RoutingMachine.jsx'

export default function MyMap({}) {
var [zoom, setZoom] = useState(8);
var [map, setMap] = useState(null);
var [animate, setAnimate] = useState(false);
var [markerPointsForRouting, setMarkerPointsForRouting] = useState([])
var [isMapInit, setIsMapInit] = useState(false)

  useEffect(() => {
  console.log("markerPointsForRouting ", markerPointsForRouting);
  },[markerPointsForRouting]);

  function addMarker(e){
    var coords = e.latlng;
    console.log("coords ", coords);
    if (markerPointsForRouting.length < 2) setMarkerPointsForRouting(markerPointsForRouting => [...markerPointsForRouting, coords]);
  }

  function saveMap(map){
    if (markerPointsForRouting.length) {
      setIsMapInit(isMapInit => true)
    }
    setMap(map)
  }

  var MAPBOX_ACCESS_TOKEN = process.env.MAPBOX_ACCESS_TOKEN;

  var locateOptions = {
    position: 'topright',
    strings: {
      title: 'Show me where I am, yo!'
    },
    onActivate: () => {} // callback before engine starts retrieving locations
  };

  return (
  <Map animate={animate} zoom={zoom}  onClick={addMarker} ref={saveMap}>
    <MapboxLayer
      accessToken={MAPBOX_ACCESS_TOKEN}
      style="mapbox://styles/mapbox/streets-v9"
    />
    <LocateControl options={locateOptions} startDirectly />

    {isMapInit &&  <Routing map={map} latLng={markerPointsForRouting} />}
  </Map>
  )
}

This is my Routing Machine component:

import React, { useState } from 'react'

import { MapLayer } from "react-leaflet";
import L from "leaflet";
import "leaflet-routing-machine";
import { withLeaflet } from "react-leaflet";

class Routing extends MapLayer {
  createLeafletElement() {
  const { map, latLng } = this.props;

  console.log("latLng ", latLng);
   var greenIcon = new L.Icon({
    iconUrl: 'https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-green.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]
  });

  var redIcon = new L.Icon({
    iconUrl: 'https://raw.githubusercontent.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]
  });

  var leafletElement = L.Routing.control({
     waypoints: [null],
     createMarker: function(i, wp, nWps) {

    console.log("i, ", i);
    console.log("wp ", wp);
    console.log("nWps ", nWps);

        if (i === 0 || i === nWps - 1) {
            return L.marker(wp.latLng, {icon: greenIcon });
        } else {
            return L.marker(wp.latLng, {icon: redIcon });
        }
    }
  }).addTo(map.leafletElement);

  leafletElement.setWaypoints(latLng)

  return leafletElement.getPlan();
 }
}

export default withLeaflet(Routing);

Thank you in advance!