1

How can i zoom on particular location or flyTo that particular location dynamically when location selected dynamically from list of cities dropdown and the getBounds around that location. I am trying to reference this answer but this can work after flyTo happens. So how can use flyTo with my code.

    useEffect(() => {
  const cityFilter = () => {
    let geocodes = JSON.parse(sessionStorage.getItem('geocode'));
    let mapData = props.allEquipData.filter((filtered) => {
      return filtered.city === selectedCity;
    });
    Promise.all(
      mapData.map(async (data) => {
        let selectedLocGeo = geocodes.filter((geo) => geo.zip == data.zipcode);
        if (selectedLocGeo.length > 0) {
          data.coordinates = [selectedLocGeo[0].latitude, selectedLocGeo[0].longitude];
        } else {
          data.coordinates = [0, 0];
        }
        return data;
      })
    )
      .then((response) => {
        let markerData = [];
        let count = 1;
        response.map((resp, index) => {
          if (resp.coordinates[0] !== 0 && resp.coordinates[1] !== 0) {
            let existingPositionIndex = markerData.findIndex(
              (mark) =>
                mark.positions && mark.positions.length && mark.positions[0] === resp.coordinates[0] && mark.positions[1] === resp.coordinates[1]
            );
            if (existingPositionIndex > -1) {
              markerData[existingPositionIndex].devices.push(resp);
            } else {
              let obj = {
                positions: resp.coordinates,
                key: 'marker' + count,
                devices: [resp],
                location: resp.city + ', ' + resp.state,
              };
              markerData.push(obj);
              count++;
            }
          }
        });

        // let group = new L.featureGroup([markerData[0].positions]);
        // mapRef.firBounds(group.getBounds());
        // console.log('oth position : ', markerData[0].positions);

        // const map = mapRef.current;
        // // console.log('map : ',map.leafletElement.flyTo);
        // // var group = new L.featureGroup([L.marker(markerData[0].positions)]);
        // // if (map) map.leafletElement.fitBounds(group.getBounds());

        // if (map) {
        //   map.flyTo(markerData[0].positions, 10);

        setFilteredMarkers(markerData);
      })
      .catch((err) => {
        console.log('Err', err);
      });
  };
  cityFilter();
}, [selectedCity]);

<Map
  center={position}
  zoom={5}
  maxZoom={100}>
  <LayersControl position='topright'>
    <LayersControl.Overlay name='Markers' checked>
      <LayerGroup>
        <MyMarkersList markers={handleMarkers(markerData)} />
      </LayerGroup>
    </LayersControl.Overlay>
  </LayersControl>
</Map>

when city will be selected from dropdown, the useEffect will be called and then it will get you the markers position based on selected city e.g [lat,log]. from this point it should flyTo that location and getBounds around it if possible.

kboul
  • 13,836
  • 5
  • 42
  • 53
DharmikSoni
  • 59
  • 1
  • 10
  • Could you provide a demo to reproduce it? – kboul Nov 10 '20 at 20:28
  • @kboul https://codesandbox.io/s/react-leaflet-demo-o7ix8 here you can find working demo. console will show filtered city coordinates when selected from dropdown and based on that need to use flyTo similar to this [demo](https://codepen.io/corneliusgdahling/pen/ZyPOYG) – DharmikSoni Nov 11 '20 at 07:22

1 Answers1

1

Add these two lines of code before setFilteredMarkers(markerData);

const {latitude, longitude} = geoCodes.find(g => g.city === selectedCity)
 map.flyTo([ longitude,latitude], 12);

You want to find the coordinates of the selected city which is inside geoCodes Object[]. You use array.find using the value of th eselectedCity to achieve that. This will be triggered every time the value in the dropdown changes.

Updated Demo

kboul
  • 13,836
  • 5
  • 42
  • 53
  • flyTo is not working as it should, i am getting correct coordinates for selected location, although flyTo goes in wrong direction or always goes to botton of the map where nothing is visible. this issue i am getting with my working model, but with codepen is working fine. why so? Here's the video link [demo](https://gofile.io/d/mQgwdF) – DharmikSoni Nov 11 '20 at 16:48
  • I am not sure why this is happening. In the demo I attached it works as it should. Probably it has to do with other part of the code in your application or something in the map setup or settings. – kboul Nov 11 '20 at 16:55
  • can you modify sandbox to use getBounds and fitBounds? – DharmikSoni Nov 11 '20 at 16:58
  • I think the result you get is sufficient. You need either a group of markers to get its bounds or another group of geographic entities to use effectively `fitBounds` around a group. I think you do not need it. Fly to centers the area around the coords of the city markers and its fine. – kboul Nov 11 '20 at 17:05
  • I am trying to reset map to initial bounds when my filteres are cleared. And also trying to setMaxBounds to not zoom out more than bounds. Can you help with this demo. It is same demo as above just little modification. [demo](https://codesandbox.io/s/react-leaflet-demo-o7ix8) – DharmikSoni Dec 02 '20 at 13:18
  • ``. For the 2nd question you need to ask a new question. It is compeltely irrelevant with the current one and please upvote the answer if it helped you. ` – kboul Dec 02 '20 at 17:56