Skip to content

Commit

Permalink
fix: nearbySearch bug in EmergencyLocation
Browse files Browse the repository at this point in the history
  • Loading branch information
akmalhisyammm committed Dec 4, 2021
1 parent fbec6c5 commit 9ead94d
Show file tree
Hide file tree
Showing 2 changed files with 95 additions and 88 deletions.
19 changes: 7 additions & 12 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,19 @@ import ReactDOM from 'react-dom';
import App from './App';
import * as serviceWorkerRegistration from './serviceWorkerRegistration';
import reportWebVitals from './reportWebVitals';
import { LoadScript } from '@react-google-maps/api';
import { AuthProvider } from 'contexts/auth';
import { PersonalContactProvider } from 'contexts/personalContact';
import { EmergencyServiceProvider } from 'contexts/emergencyService';

const googleMapsApiKey = `${process.env.REACT_APP_GOOGLE_MAPS_API_KEY}`;

ReactDOM.render(
<React.StrictMode>
<LoadScript googleMapsApiKey={googleMapsApiKey} libraries={['places']}>
<AuthProvider>
<EmergencyServiceProvider>
<PersonalContactProvider>
<App />
</PersonalContactProvider>
</EmergencyServiceProvider>
</AuthProvider>
</LoadScript>
<AuthProvider>
<EmergencyServiceProvider>
<PersonalContactProvider>
<App />
</PersonalContactProvider>
</EmergencyServiceProvider>
</AuthProvider>
</React.StrictMode>,
document.getElementById('root')
);
Expand Down
164 changes: 88 additions & 76 deletions src/pages/main/EmergencyLocation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,45 +3,50 @@ import {
IonFab,
IonFabButton,
IonIcon,
IonSearchbar,
IonTitle,
IonToolbar,
} from '@ionic/react';
import { Geolocation } from '@capacitor/geolocation';
import { GoogleMap, Marker } from '@react-google-maps/api';
import { GoogleMap, Marker, useLoadScript } from '@react-google-maps/api';
import { locateOutline } from 'ionicons/icons';
import { useEffect, useState } from 'react';
import { useCallback, useEffect, useRef, useState } from 'react';

import Layout from 'components/layout';

interface Coordinates {
type Coordinates = {
lat: number;
lng: number;
}
};

interface Location {
center: {
lat: any;
lng: any;
};
coordsResult: [];
}
const options: google.maps.MapOptions = {
disableDefaultUI: true,
zoomControl: true,
};

const center: Coordinates = {
lat: -6.257377926995551,
lng: 106.61829861017398,
};

const libraries: any = ['places'];

const EmergencyLocation: React.FC = () => {
const [currentPosition, setCurrentPosition] = useState<Coordinates>({
lat: -6.257377926995551,
lng: 106.61829861017398,
});
const [emergencyLocation, setEmergencyLocation] = useState<Location>({
center: currentPosition,
coordsResult: [],
const [currentPosition, setCurrentPosition] = useState<Coordinates>(center);
const [nearbyPlaces, setNearbyPlaces] = useState<
google.maps.places.PlaceResult[]
>([]);

const { isLoaded, loadError } = useLoadScript({
id: 'map',
googleMapsApiKey: `${process.env.REACT_APP_GOOGLE_MAPS_API_KEY}`,
libraries,
});
const [isGetCurrentPosition, setIsGetCurrentPosition] =
useState<boolean>(true);

const mapRef = useRef<google.maps.Map>();

useEffect(() => {
getCurrentPosition();
setIsGetCurrentPosition(false);
}, [isGetCurrentPosition]);
}, []);

const getCurrentPosition = async () => {
const coordinates = await Geolocation.getCurrentPosition({
Expand All @@ -54,89 +59,96 @@ const EmergencyLocation: React.FC = () => {
});
};

const onMapLoad = async (map: google.maps.Map) => {
await getCurrentPosition();
const onMapLoad = useCallback((map) => {
mapRef.current = map;
}, []);

const fetchPlaces = async (keyword?: string) => {
const request = {
location: currentPosition,
radius: 1000,
type: 'hospital',
radius: 2000,
type: keyword ?? 'hospital',
};

const service = new window.google.maps.places.PlacesService(map);
if (!mapRef.current) return;

const coords: any = [];
const service = new window.google.maps.places.PlacesService(mapRef.current);

service.nearbySearch(request, (results, status) => {
if (status === google.maps.places.PlacesServiceStatus.OK && results) {
for (let i = 0; i < results.length; i++) {
coords.push(results[i]);
}

setEmergencyLocation({
center: {
lat: results[0].geometry?.location?.lat,
lng: results[0].geometry?.location?.lng,
},
coordsResult: coords,
});
console.log(results);
setNearbyPlaces(results);
}
});

console.log(coords);
};

return (
<Layout title="Lokasi Layanan Darurat">
<IonToolbar color="primary">
<IonSearchbar
color="light"
placeholder="Cari Lokasi Layanan Darurat..."
style={{
'--border-radius': '24px',
'--box-shadow': '0 0 0 1px var(--ion-color-dark)',
margin: '12px 0 8px',
padding: '0 6px',
}}
/>

<IonTitle className="ion-margin-vertical">Pilih Lokasi</IonTitle>
<div
style={{
marginBottom: '12px',
margin: '12px',
overflow: 'auto',
whiteSpace: 'nowrap',
}}
>
<IonChip outline style={{ borderColor: '#ffffff' }}>
<IonChip
outline
style={{ borderColor: '#ffffff' }}
onClick={() => fetchPlaces('hospital')}
>
Rumah Sakit
</IonChip>
<IonChip
outline
style={{ borderColor: '#ffffff' }}
onClick={() => fetchPlaces('police')}
>
Polisi
</IonChip>
<IonChip
outline
style={{ borderColor: '#ffffff' }}
onClick={() => fetchPlaces('fire_station')}
>
Stasiun Damkar
</IonChip>
</div>
</IonToolbar>

<div style={{ width: '100%', height: '100%', paddingBottom: '112px' }}>
<GoogleMap
mapContainerStyle={{
width: '100%',
height: '100%',
}}
center={currentPosition}
zoom={14}
onLoad={(map) => onMapLoad(map)}
>
<Marker position={currentPosition} />
{isLoaded && (
<div style={{ width: '100%', height: '100%', paddingBottom: '112px' }}>
<GoogleMap
id="map"
onLoad={onMapLoad}
mapContainerStyle={{
width: '100%',
height: '100%',
}}
center={currentPosition}
zoom={15}
options={options}
>
<Marker position={currentPosition} />

{nearbyPlaces &&
nearbyPlaces.map(
(place: google.maps.places.PlaceResult, i: number) => (
<Marker
key={i}
position={place.geometry?.location as google.maps.LatLng}
/>
)
)}
</GoogleMap>
</div>
)}

{emergencyLocation.coordsResult &&
emergencyLocation.coordsResult.map((result: any, i: number) => (
<Marker key={i} position={result.geometry.location} />
))}
</GoogleMap>
</div>
{loadError && <h1>Google maps Error!</h1>}

<IonFab horizontal="start" vertical="bottom" slot="fixed">
<IonFabButton
color="primary"
onClick={() => setIsGetCurrentPosition(true)}
>
<IonFabButton color="primary" onClick={getCurrentPosition}>
<IonIcon icon={locateOutline} />
</IonFabButton>
</IonFab>
Expand Down

0 comments on commit 9ead94d

Please sign in to comment.