I tried everything, but geolib is not working in my React code.
import * as geolib from "geolib";
import axios from "axios";
import { useEffect, useState } from "react";
const ShowNearestProviders = () => {
const [distances, setDistances] = useState([]);
// Coordinates from A to B
console.log(geolib.getDistanceFromLine);
useEffect(() => {
axios
.get("http://localhost:5000/api/providers")
.then((response) => {
const patientCoordinates = [50.038544514092784, 8.561901802445224];
const dropOffCoordinates = [51.23347403817581, 6.7931030255761575];
const updatedProviders = response.data.map((provider) => {
const providerCoordinates = [provider.lat, provider.lng];
const distance = geolib.getDistanceFromLine(
providerCoordinates,
patientCoordinates,
dropOffCoordinates
);
const result = Math.round(geolib.convertDistance(distance, "km"));
return { ...provider, distance: result };
});
setDistances(updatedProviders);
console.log("Verbände erfolgreich geladen.");
})
.catch((error) => console.log(error));
}, []);
return (
<div>
{distances.map((provider) => (
<p key={provider.name}>
{provider.name}: {provider.distance} km
</p>
))}
</div>
);
};
export default ShowNearestProviders;
I have an /api/data/providers.json file and within /api/ I have server.js with Express, it looks like that:
const express = require("express");
const cors = require("cors");
const app = express();
const path = require("path");
app.use(cors());
app.get("/api/providers", (req, res) => {
res.sendFile(path.join(__dirname, "data/providers.json"));
});
app.listen(5000, () => console.log("Server started on port 5000"));
I get the following error:
ƒ getDistanceFromLine(point, lineStart, lineEnd) {
var accuracy = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1;
var d1 = (0, _getDistance.default)(lineStart, point, accurac…
installHook.js:1608 ƒ getDistanceFromLine(point, lineStart, lineEnd) {
var accuracy = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1;
var d1 = (0, _getDistance.default)(lineStart, point, accurac…
2ShowNearestProviders.jsx:29 TypeError: Cannot read properties of undefined (reading 'toString')
at isDecimal (isDecimal.js:1:1)
at toDecimal (toDecimal.js:1:1)
at getLatitude (getLatitude.js:1:1)
at getDistance (getDistance.js:1:1)
at Object.getDistanceFromLine (getDistanceFromLine.js:1:1)
at ShowNearestProviders.jsx:19:1
at Array.map (<anonymous>)
at ShowNearestProviders.jsx:17:1
Any idea what is wrong? I tried geolib before in a vanilla javascript file and it worked. Now integrating it into React, I get these issues.
If the problem comes with geolib, is there a library that provides functions like that but that works with React?
Thank you in advance!