perliedman / leaflet-routing-machine

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

TypeError: Cannot read property 'getSize' of undefined #612

Open antonioOrtiz opened 3 years ago

antonioOrtiz commented 3 years ago

Not sure how this can be happening as I am using useRef to pass a reference of my map to the Routing Machine component...

But first here are my dependencies...

        "react-leaflet": "^2.7.0",
        "leaflet": "^1.7.1",
        "leaflet-control-geocoder": "^1.13.0",
        "leaflet-geosearch": "^3.0.6",
        "leaflet-routing-machine": "^3.2.12",

This is my Map component!

import React, { useState, useEffect, useRef } from 'react'
import { Map, Marker } from 'react-leaflet';
import LocateControl from '../LocateControl/LocateControl.jsx';
import MapboxLayer from '../MapboxLayer/MapboxLayer.jsx';
import L from "leaflet";
import LCG from 'leaflet-control-geocoder';
import Routing from '../RoutingMachine/RoutingMachine.jsx'

export default function MyMap({getAddressFromLatLong, hillfinderFormButtonRef, setCurrentLocation, setCurrentDestination}) {
  var [zoom, setZoom] = useState(4);
  var [map, setMap] = useState(null);
  var [animate, setAnimate] = useState(false);
  var [draggable, setDraggable] = useState(true);
  var [markerData, setMarkerData] = useState([]);
  var [amountOfMarkers, setAmountOfMarkers] = useState(0);
  var [markerPointsForRouting, setMarkerPointsForRouting] = useState(null)
  var [mapCenter, setMapCenter] = useState(null)
  var [isMapInit, setIsMapInit] = useState(false)

  useEffect(() => {
    hillfinderFormButtonRef.current = clearMarkers;

    return() => {
     hillfinderFormButtonRef.current = null;
    }
  });

  useEffect(() => {
     if (map ){

      map.on('load', function (result) {
        setMapCenter(mapCenter=> result.sourceTarget._lastCenter)
      })

     }
  });

  useEffect(() => {
    if (markerData.length === 2){
      setMarkerPointsForRouting(markerData);
    }
  });

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]
});

function addMarker(e){
  // setShowMarkers(showMarkers => !showMarkers)
  var coords = e.latlng;
  if (amountOfMarkers < 2) {
    setAmountOfMarkers(amountOfMarkers => amountOfMarkers + 1)
    updateAddressFromMarker(amountOfMarkers, coords);
    setMarkerData(markerData => [...markerData, coords]);
  }
  else null;
}

function updateMarker(e){
  var markerLatLng = e.target.getLatLng(); //get marker LatLng
  var markerIndex = e.target.options.marker_index;
  updateAddressFromMarker(markerIndex, markerLatLng)

  setMarkerData(markerData => {
   markerData[markerIndex] = markerLatLng;
   return markerData;
  })
}

function updateAddressFromMarker(marker, latLng){
    var geocoder = new L.Control.geocoder();
     geocoder.options.geocoder.reverse(latLng, 5, (address)=>{
      getAddressFromLatLong(marker, address[0].name)
    }, null)
}

function clearMarkers(){
  setMarkerData(markerData => [], ...markerData);
  setAmountOfMarkers(0);
  setCurrentLocation(''), setCurrentDestination('')
}

function toggleAnimate() {
  setAnimate(animate => !animate);
}

  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
  };

    var mapRef = useRef();

    useEffect(()=>{
      var {current = {}} = mapRef;
      var { leafletElement: map } = current;
      setIsMapInit(isMapInit=> !isMapInit)
      setMap(map);
    },[])

  return (
        <Map center={markerPointsForRouting} animate={animate} zoom={zoom} onClick={addMarker} ref={mapRef}>
        { markerData.map((element, index) => (
            <Marker
              key={index}
              marker_index={index}
              position={element}
              draggable={draggable}
              onDragend={updateMarker}
              icon={index === 0 ? greenIcon : redIcon}
            />
          ))}

          <MapboxLayer
            accessToken={MAPBOX_ACCESS_TOKEN}
            style="mapbox://styles/mapbox/streets-v9"
          />
          <LocateControl options={locateOptions} startDirectly />

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

  )
}

And this is my Routing Machine component...

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

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

    var startingCoords = {
      lat: latLng[0].lat,
      lng: latLng[0].lng
    }

    console.log("startingCoords.lat ", startingCoords.lat);
    console.log("startingCoords.lng", startingCoords.lng);

    var endingCoords = {
      lat: latLng[0].lat,
      lng: latLng[1].lng
    }

    var leafletElement = new L.Routing.control({
    waypoints: [L.latLng(startingCoords.lat, startingCoords.lng), L.latLng(endingCoords.lat, endingCoords.lng)]
        }).addTo(myMapRef.leafletElement);
        return leafletElement.getPlan();
      }
    }

export default withLeaflet(Routing);

Interestingly enough in firefox this is my error:

TypeError: map is undefined

azica commented 2 years ago

Hi Antoninio, ihave the same bugs. Did you solve it?

curtisy1 commented 2 years ago

@antonioOrtiz is this still happening in your hillfinder project so I could take a look at it? If not, then would you mind sharing a reproducible test project or codepen, @azica?