Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save oleg1994/9f5e956a3f99752a94bdde06ad246097 to your computer and use it in GitHub Desktop.
Save oleg1994/9f5e956a3f99752a94bdde06ad246097 to your computer and use it in GitHub Desktop.
const [routeCoordinates, setRouteCoordinates] = useState([]);
useEffect(() => {
const getRoute = async () => {
const apiKey = process.env.EXPO_PUBLIC_googleMaps_ApiKey;
let userCoordinates = null;
try {
const location = await Location.getLastKnownPositionAsync();
userCoordinates = location;
} catch (error) {
console.error("Error fetching user location at func fetchStationData:", error);
}
const origin = `${userCoordinates?.coords?.latitude},${userCoordinates?.coords?.longitude}`; // Los Angeles
const destination = `${markerSelected?.address?.location?.latitude},${markerSelected?.address?.location?.longitude}`; // Los Angeles
const url = `https://maps.googleapis.com/maps/api/directions/json?origin=${origin}&destination=${destination}&key=${apiKey}`;
try {
const response = await axios.get(url);
const points = response.data.routes[0].overview_polyline.points;
const route = decodePolyline(points);
setRouteCoordinates(route);
} catch (error) {
console.error("Error fetching route:", error);
}
};
if (markerSelected) {
getRoute();
} else {
setRouteCoordinates(null);
}
}, [markerSelected]);
const decodePolyline = (t) => {
const points = [];
let index = 0,
len = t.length;
let lat = 0,
lng = 0;
while (index < len) {
let b,
shift = 0,
result = 0;
do {
b = t.charCodeAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
const dlat = result & 1 ? ~(result >> 1) : result >> 1;
lat += dlat;
shift = 0;
result = 0;
do {
b = t.charCodeAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
const dlng = result & 1 ? ~(result >> 1) : result >> 1;
lng += dlng;
points.push({
latitude: lat / 1e5,
longitude: lng / 1e5,
});
}
return points;
};
{routeCoordinates && (
<Polyline
coordinates={routeCoordinates}
strokeColor="#EB3FD2" // Change color to your preference
strokeWidth={3}
/>
)}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment