I have a component where i get the distance from one point to another, with Google Maps (DirectionsRenderer).
What i want, is to use this data in a h1
JavaScript
x
2
1
directionsRenderer.directions.routes[0].legs[0].distance.text;
2
This is my return
JavaScript
1
35
35
1
return (
2
<>
3
<div>
4
<GoogleMap
5
mapContainerStyle={mapContainerStyle}
6
zoom={8}
7
center={center}
8
onLoad={onMapLoad}
9
>
10
{response !== null && (
11
<DirectionsRenderer
12
options={{
13
directions: response,
14
}}
15
onLoad={(directionsRenderer) => {
16
distanceInKm =
17
directionsRenderer.directions.routes[0].legs[0].distance.text;
18
console.log("I wan't this data ->" + distanceInKm);
19
}}
20
/>
21
)}
22
23
<DirectionsService
24
options={DirectionsServiceOption}
25
callback={directionsCallback}
26
/>
27
</GoogleMap>
28
</div>
29
{/* THIS IS WHERE I WANT TO USE THE DATA */}
30
<h1 id="calculatedDistance">{distanceInKm} km væk</h1>
31
32
</>
33
);
34
};
35
EDIT:
ShowProduct.js (This is where i get the distance)
JavaScript
1
145
145
1
import React, {
2
useContext,
3
useEffect,
4
useState,
5
useCallback,
6
useRef,
7
} from "react";
8
import { Link } from "react-router-dom";
9
10
import {
11
GoogleMap,
12
useLoadScript,
13
DirectionsService,
14
DirectionsRenderer,
15
} from "@react-google-maps/api";
16
17
// context
18
import DbContext from "../../../context/DbContext";
19
20
21
// MAP
22
const libraries = ["places", "directions"];
23
const mapContainerStyle = {
24
width: "100%",
25
height: "50vh",
26
};
27
28
29
const ShowProduct = (props) => {
30
const [post, setPost] = useState();
31
let [distanceInKm, setDistanceInKm] = useState(0);
32
const context = useContext(DbContext);
33
useEffect(() => {
34
context.getProduct(props.match.params.id).then((x) => setPost(x));
35
36
37
}, [context.existsUser()]);
38
39
40
useEffect(() => {
41
context.getProduct(props.match.params.id).then((x) => setPost(x));
42
43
}, []);
44
45
// map
46
const { isLoaded, loadError } = useLoadScript({
47
googleMapsApiKey: "YOUR_API_KEY",
48
libraries,
49
});
50
const [currentPosition, setCurrentPosition] = useState({});
51
52
// destination will come from Database
53
let [destination2, setDestination2] = useState(
54
"57.021779738464396, 9.711555234340288"
55
);
56
57
const success = (position) => {
58
let currentPosition = {
59
lat: position.coords.latitude,
60
lng: position.coords.longitude,
61
};
62
63
setCurrentPosition(currentPosition);
64
65
};
66
let [origin2, setOrigin2] = useState();
67
68
useEffect(() => {
69
navigator.geolocation.getCurrentPosition(success);
70
71
}, []);
72
const [response, setResponse] = useState(null);
73
74
const directionsCallback = (response) => {
75
console.log(response);
76
77
if (response !== null) {
78
if (response.status === "OK") {
79
setResponse(response);
80
} else {
81
console.log("response: ", response);
82
}
83
}
84
};
85
86
const mapRef = useRef();
87
const onMapLoad = useCallback((map) => {
88
mapRef.current = map;
89
}, []);
90
if (loadError) return "Error loading maps";
91
if (!isLoaded) return "loading maps";
92
93
94
destination2 = post?.latitude + ", " + post?.longitude;
95
96
const DirectionsServiceOption = {
97
destination: destination2,
98
origin: currentPosition.lat + ", " + currentPosition.lng,
99
travelMode: "DRIVING",
100
};
101
102
return (
103
<>
104
<div>
105
<GoogleMap
106
mapContainerStyle={mapContainerStyle}
107
zoom={8}
108
center={center}
109
onLoad={onMapLoad}
110
>
111
{response !== null && (
112
<DirectionsRenderer
113
options={{
114
directions: response,
115
}}
116
onLoad={(directionsRenderer) => {
117
distanceInKm = directionsRenderer.directions
118
.routes[0].legs[0].distance.text;
119
setDistanceInKm(distanceInKm);
120
}}
121
/>
122
)}
123
124
<DirectionsService
125
options={DirectionsServiceOption}
126
127
callback={directionsCallback}
128
/>
129
</GoogleMap>
130
</div>
131
132
<h1 id="calculatedDistance">{distanceInKm} km væk</h1>
133
134
</>
135
);
136
};
137
138
const styleLikeButton = {
139
right: 23,
140
bottom: 10,
141
};
142
143
export default ShowProduct;
144
145
ProductCard.js (This is where want to use it)
JavaScript
1
90
90
1
import React, {
2
useContext,
3
useEffect,
4
useState,
5
useRef,
6
useCallback,
7
} from "react";
8
import ProductCard from "react-tinder-card";
9
import database from "../../../firebase";
10
import "../../../styles/ProductCards.css";
11
import { Link } from "react-router-dom";
12
13
// Context
14
import DbContext from "../../../context/DbContext";
15
16
17
const ProductCards = () => {
18
const [products, setProducts] = useState([]);
19
const context = useContext(DbContext);
20
21
useEffect(() => {
22
if (context.existsUser() == null) {
23
24
window.location.href = "/login";
25
}
26
27
context.getProducts().then((r) => setProducts(r));
28
29
console.log(products);
30
}, [context]);
31
32
// TJEK swipe direction
33
const onSwipe = (direction) => {
34
35
if (direction == "right") {
36
// product to interestsList
37
console.log("Interesseret!!!");
38
}
39
console.log("You swiped: " + direction);
40
};
41
42
43
const onCardLeftScreen = (myIdentifier) => {
44
console.log(myIdentifier + " left the screen");
45
};
46
47
return (
48
<>
49
<div>
50
{products.length > 0 ? (
51
<div className="productCards__cardContainer">
52
{products.map((product) => (
53
<ProductCard
54
className="swipe"
55
key={product.title}
56
preventSwipe={["down"]}
57
onSwipe={onSwipe}
58
onCardLeftScreen={() => onCardLeftScreen(product.id)}
59
>
60
61
{/* THIS IS WHERE I WOULD LIKE TO USE THE DISTANCE */}
62
<h1>{distanceInKm} km væk</h1>
63
<h4 className="price">{product?.price} kr.</h4>
64
65
<Link
66
className="product_title"
67
to={`/showproduct/${product.id}`}
68
>
69
{product.title}
70
</Link>
71
72
</ProductCard>
73
))}
74
</div>
75
) : (
76
"Loading..."
77
)}
78
</div>
79
80
81
</>
82
);
83
};
84
85
86
87
88
export default ProductCards;
89
90
Advertisement
Answer
You need to set up a state using useState hook, before your return:
JavaScript
1
2
1
const [distanceInKm, setDistanceInKm] = useState(0);
2
Then in your onLoad callback, you need to set the actual value of the distance:
JavaScript
1
6
1
onLoad={(directionsRenderer) => {
2
distanceInKm = directionsRenderer.directions
3
.routes[0].legs[0].distance.text;
4
setDistanceInKm(distanceInKm);
5
}}
6
And finally in your h1 you can now use the value:
JavaScript
1
2
1
<h1 id="calculatedDistance">{distanceInKm} km væk</h1>
2