Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat: Added Approx. Distance on resource card #287

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions components/DetailedHome.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,11 @@ import HomeTabs from '@components/HomeTabs';
import { useRouter } from 'next/router';
import { isVerified } from '../lib/utils';
import MapContainer from './MapContainer';
import useCurrentLocation from '@hooks/useCurrentLocation';

export default function DetailedHome({ state, district, type }) {
const { locale } = useLocaleContext();
const { location: currentLocation, error } = useCurrentLocation();
const t = useLocale(locale, 'home');
const router = useRouter();

Expand Down Expand Up @@ -209,6 +211,7 @@ export default function DetailedHome({ state, district, type }) {
{tabVal === 'result' && (
<SearchResult
changeTabs={changeTabs}
currentLocation={currentLocation}
type={resourceChosen}
district={districtChosen}
resources={resources[resourceChosen]}
Expand All @@ -223,6 +226,7 @@ export default function DetailedHome({ state, district, type }) {
{tabVal === 'maps' && (
<MapContainer
resourceChosen={resourceChosen}
currentLocation={currentLocation}
resources={locationResources[resourceChosen]}
district={getStateIfDistrictAll(stateChosen, districtChosen)}
state={stateChosen}
Expand Down
45 changes: 12 additions & 33 deletions components/MapContainer.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { fetchLocation } from '../lib/external';
import { faDirections } from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { tabsInfo } from '@lib/tabs';
import { getHaversineDistance } from '@lib/utils';
import MapInfoWindow from './MapInfoWindow';
import Badge from './Badge';

Expand All @@ -20,20 +21,10 @@ export class MapContainer extends Component {
activeMarker: {},
selectedPlace: {},
centerLocation: null,
currentLocation: null,
zoom: defaultZoom
};

componentDidMount() {
const that = this;
navigator.geolocation.getCurrentPosition(function (position) {
that.setState({
currentLocation: {
lat: position.coords.latitude,
lng: position.coords.longitude
}
});
});
if (this.props.district || this.props.state) {
fetchLocation(`${this.props.district} ${this.props.state}`)
.then((response) => {
Expand All @@ -45,7 +36,8 @@ export class MapContainer extends Component {
});
}
})
.catch(() => {
.catch((err) => {
console.log('Error while fetching searched location\'s lattitude and longitude: ', err);
this.setState({
centerLocation: defaultLocation,
zoom: defaultZoom
Expand All @@ -71,22 +63,6 @@ export class MapContainer extends Component {
}
};

getHaversineDistance = (firstLocation, secondLocation) => {
if (!firstLocation) return null;
const earthRadius = 6371; // km
const diffLat = ((secondLocation.lat - firstLocation.lat) * Math.PI) / 180;
const diffLng = ((secondLocation.lng - firstLocation.lng) * Math.PI) / 180;
const arc =
Math.cos((firstLocation.lat * Math.PI) / 180) *
Math.cos((secondLocation.lat * Math.PI) / 180) *
Math.sin(diffLng / 2) *
Math.sin(diffLng / 2) +
Math.sin(diffLat / 2) * Math.sin(diffLat / 2);
const line = 2 * Math.atan2(Math.sqrt(arc), Math.sqrt(1 - arc));
const distance = earthRadius * line;
return distance.toFixed();
};

openInGoogleMap = () => {
const lat = this.state.selectedPlace?.info.latitude;
const lng = this.state.selectedPlace?.info.longitude;
Expand All @@ -113,7 +89,7 @@ export class MapContainer extends Component {
position={this.state.centerLocation}
onClick={this.onMarkerClick}
name={'Searched Location'}
currentLocation={true}
isCurrentLocation={true}
/>
{this.props.resources.map((resource) => {
return (
Expand All @@ -123,7 +99,7 @@ export class MapContainer extends Component {
key={resource.external_id}
name={resource.title}
info={resource}
distance={this.getHaversineDistance(this.state.currentLocation, {
distance={getHaversineDistance(this.props.currentLocation, {
lat: resource.latitude,
lng: resource.longitude
})}
Expand All @@ -138,9 +114,11 @@ export class MapContainer extends Component {
<h1 class="text-black-800">
<strong>{this.state.selectedPlace.info?.title ||
this.state.selectedPlace.name}</strong>
<Badge status={this.state.selectedPlace.info?.verification_status} />
{!this.state.selectedPlace?.isCurrentLocation && (
<Badge status={this.state.selectedPlace.info?.verification_status} />
)}
</h1>
{!this.state.selectedPlace?.currentLocation && (
{!this.state.selectedPlace?.isCurrentLocation && (
<>
{this.state.selectedPlace.info?.phone_1 && (
<strong className="text-purple-500">
Expand Down Expand Up @@ -175,7 +153,7 @@ export class MapContainer extends Component {
icon={faDirections}
className="w-2 h-2 dark:text-primary-500"
/>
<span className="text-xs ml-2">Directions</span>
<span className="text-xs ml-2">Get Directions</span>
</button>
{this.state.selectedPlace.distance && (
<p>
Expand All @@ -198,5 +176,6 @@ export default GoogleApiWrapper((props) => ({
resourceChoosen: props.resourceChosen,
resources: props.resources,
districtChoosen: props.districtChoosen,
stateChoosen: props.stateChoosen
stateChoosen: props.stateChoosen,
currentLocation: props.currentLocation
}))(MapContainer);
20 changes: 18 additions & 2 deletions components/ResourceCard.jsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
import React from 'react';
import TimeAgo from 'timeago-react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import SocialSharing from '@components/SocialSharing';
import { faBed, faEnvelope, faHeartbeat, faLink, faMapMarkerAlt, faDirections, faMedkit, faMobileAlt, faPhoneAlt, faProcedures } from '@fortawesome/free-solid-svg-icons';
import { copyTextGenerator, getGoogleMapsDirectionLink } from '@lib/utils';
import { useRouter } from 'next/router';
import { getHaversineDistance } from '@lib/utils';
import Badge from './Badge';
import Description from './Description';
import TimeAgo from 'timeago-react';

import FeedbackCounter from './FeedbackCounter';

const ResourceCard = ({ data, type: filterType }) => {
const ResourceCard = ({ data, type: filterType, currentLocation }) => {

// General Data
const { title, district } = data;
Expand Down Expand Up @@ -188,6 +190,20 @@ const ResourceCard = ({ data, type: filterType }) => {
{/* TODO: Waiting for Endpoint from Backend */}
{/* <FeedbackCounter upvotes={upvotes} downvotes={downvotes} /> */}
</div>
<div className="flex items-center mx-1 mt-2 xs:my-0 xs:space-x-2">
{ currentLocation && latitude && longitude && (
<span className="text-xs mt-2 xs:my-0">
<span className="text-secondary-400 dark:text-primary-300">Approximately</span>
<span className="font-bold">
&nbsp;{getHaversineDistance(currentLocation, {
lat: latitude,
lng: longitude
})} Kms
</span>
<span className="text-secondary-400 dark:text-primary-300">&nbsp;from your location</span>
</span>
)}
</div>
</div>
</div>
);
Expand Down
4 changes: 2 additions & 2 deletions components/SearchResult.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { filterResourcesBy } from '@lib/utils';
import React, { useState } from 'react';
import ResourceCard from './ResourceCard';
import NoResultFound from './NoResultFound';
const SearchResult = ({ resources, type, district, changeTabs }) => {
const SearchResult = ({ resources, type, district, changeTabs, currentLocation }) => {
const [selectedFilter, setSelectedFilter] = useState('show_all');
const resourcesListing = filterResourcesBy(resources, selectedFilter);
const noData = resourcesListing.length === 0 && selectedFilter === 'show_all';
Expand Down Expand Up @@ -64,7 +64,7 @@ const SearchResult = ({ resources, type, district, changeTabs }) => {
{resourcesListing.length > 0 ? (
resourcesListing.map((resource) => {
return (
<ResourceCard key={resource.external_id} type={type} data={resource} />
<ResourceCard key={resource.external_id} type={type} data={resource} currentLocation={currentLocation} />
);
})
) : (
Expand Down
35 changes: 35 additions & 0 deletions hooks/useCurrentLocation.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { useState, useEffect } from 'react';

const useCurrentLocation = () => {
const [error, setError] = useState();
const [location, setLocation] = useState();

// Success handler for geolocation's `getCurrentPosition` method
const handleSuccess = position => {
const { latitude, longitude } = position.coords;

setLocation({
lat: latitude,
lng: longitude
});
};

// Error handler for geolocation's `getCurrentPosition` method
const handleError = error => {
setError(error.message);
};

useEffect(() => {
// If the geolocation is not defined in the used browser you can handle it as an error
if (!navigator.geolocation) {
setError('Geolocation is not supported.');
return;
}
navigator.geolocation.getCurrentPosition(handleSuccess, handleError, {
timeout: 1000 * 60 * 1 // 1 min (1000 ms * 60 sec * 1 minute = 60 000ms)
});
}, []);
return { location, error };
};

export default useCurrentLocation;
16 changes: 16 additions & 0 deletions lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -173,3 +173,19 @@ export const filterResourcesBy = (list, type) => {
return '';
}
}

export const getHaversineDistance = (firstLocation, secondLocation) => {
if (!firstLocation) return null;
const earthRadius = 6371; // km
const diffLat = ((secondLocation.lat - firstLocation.lat) * Math.PI) / 180;
const diffLng = ((secondLocation.lng - firstLocation.lng) * Math.PI) / 180;
const arc =
Math.cos((firstLocation.lat * Math.PI) / 180) *
Math.cos((secondLocation.lat * Math.PI) / 180) *
Math.sin(diffLng / 2) *
Math.sin(diffLng / 2) +
Math.sin(diffLat / 2) * Math.sin(diffLat / 2);
const line = 2 * Math.atan2(Math.sqrt(arc), Math.sqrt(1 - arc));
const distance = earthRadius * line;
return distance.toFixed();
};