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='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
< /MapContainer >
map.getBounds()
– Bowlds