How to locate react-leaflet map to user's current position and get the borders for this map?
Asked Answered
L

1

9

I need to locate react-leaflet map to user's current position and get the borders for this map. I tried to apply the following code, but faced the error:

TypeError: Cannot read property 'locate' of undefined (anonymous function)

Please help me!

import React, { useState, useEffect, useRef } from 'react';
import restaurantsInfo from "./RestaurantsList.json";
import "./App.css";
import { MapContainer, Marker, Popup, TileLayer, useMapEvents } from "react-leaflet";
import { Icon, latLng } from "leaflet";
import Restaurants from "./Restaurants.js";
import LocationMarker from "./LocationMarker.js";
import L from 'leaflet';

const myLocation = [49.1951, 16.6068];
const defaultZoom = 13;

export default function App() {

  const mapRef = useRef();
  useEffect(() => {
    const { current = {} } = mapRef;
    const { leafletElement: map } = current;
    map.locate({
    setView: true,
    });
    map.on('locationfound', handleOnLocationFound);
  }, []);

  function handleOnLocationFound(event) {
    const { current = {} } = mapRef;
    const { leafletElement: map } = current;
    const latlng = event.latlng;
    const radius = event.accuracy;
    const circle = L.circle(latlng, radius);
    circle.addTo(map);
  }

  return (
    <div class="container">
    <div style={{height: '400px', width: '500px'}} class="map">
    
    <MapContainer ref={mapRef} center={myLocation} zoom={defaultZoom} scrollWheelZoom={false}>
    <TileLayer
      attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
      url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
    />
< /MapContainer >
Limnology answered 5/3, 2021 at 22:1 Comment(1)
you can get ther bounds of the map with map.getBounds()Bowlds
M
10

You need a custom component that will do that job and will be child of MapContainer. Get the bounding box from locationfound event.bounds

 function LocationMarker() {
    const [position, setPosition] = useState(null);
    const [bbox, setBbox] = useState([]);

    const map = useMap();

    useEffect(() => {
      map.locate().on("locationfound", function (e) {
        setPosition(e.latlng);
        map.flyTo(e.latlng, map.getZoom());
        const radius = e.accuracy;
        const circle = L.circle(e.latlng, radius);
        circle.addTo(map);
        setBbox(e.bounds.toBBoxString().split(","));
      });
    }, [map]);

    return position === null ? null : (
      <Marker position={position} icon={icon}>
        <Popup>
          You are here. <br />
          Map bbox: <br />
          <b>Southwest lng</b>: {bbox[0]} <br />
          <b>Southwest lat</b>: {bbox[1]} <br />
          <b>Northeast lng</b>: {bbox[2]} <br />
          <b>Northeast lat</b>: {bbox[3]}
        </Popup>
      </Marker>
    );
  }

Use it here

<MapContainer
      center={[49.1951, 16.6068]}
      ...
      <LocationMarker />
 </MapContainer>

Demo

Merbromin answered 6/3, 2021 at 8:32 Comment(4)
Ohh, great it works, thank you!!! I have one more question. How can I use bbox to check If some of my markers is inside the map? When I try to apply: if (bbox.contains(marker.getPosition())===true) or this if ((bbox[1] < marker.lat< bbox[3])&& (bbox[2] <marker.long <bbox[4])) I got the error: bbox is not defined I don’t know how to return bbox from function LocationMarker().Limnology
Please accept the answer since it solved your issue. Check this post and this post if you are new to SO. Regarding your question please ask in a new thread as it a new question regarding your original post and I will try to help you.Merbromin
Thank you for your advice. I am new and my new question is here: #66509689Limnology
for me raises this: Cannot convert undefined or null to objectHassiehassin

© 2022 - 2024 — McMap. All rights reserved.