searchResultComponent.tsx 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. import {
  2. View,
  3. Text,
  4. StyleSheet,
  5. Pressable,
  6. Image,
  7. ImageSourcePropType,
  8. TouchableWithoutFeedback,
  9. Keyboard,
  10. ActivityIndicator
  11. } from 'react-native';
  12. import React, { useState, useEffect, useRef, useMemo } from 'react';
  13. import { SafeAreaView } from 'react-native-safe-area-context';
  14. import MapView from 'react-native-maps';
  15. import * as Location from 'expo-location';
  16. import { router, useLocalSearchParams } from 'expo-router';
  17. import { ArrowIconSvg, CheckMarkLogoSvg } from '../global/SVG';
  18. import NormalInput from '../global/normal_input';
  19. import BottomSheet, { BottomSheetScrollView } from '@gorhom/bottom-sheet';
  20. import { chargeStationService } from '../../service/chargeStationService';
  21. import { PROVIDER_GOOGLE, Marker, Region } from 'react-native-maps';
  22. import { calculateDistance } from '../global/distanceCalculator';
  23. interface TabItem {
  24. imgURL?: ImageSourcePropType | undefined;
  25. date: string;
  26. time: string;
  27. chargeStationName: string;
  28. chargeStationAddress: string;
  29. distance: string;
  30. stationID?: string;
  31. longitude?: number;
  32. latitude?: number;
  33. lat?: number;
  34. lng?: number;
  35. }
  36. const dummyTabItems: TabItem[] = [
  37. {
  38. imgURL: require('../../assets/dummyStationPicture.png'),
  39. date: '今天',
  40. time: '16:30',
  41. chargeStationName: '觀塘偉業街充電站',
  42. chargeStationAddress: '九龍觀塘偉業街143號地下',
  43. distance: '400米',
  44. latitude: 22.31337,
  45. longitude: 114.21823
  46. },
  47. {
  48. imgURL: require('../../assets/dummyStationPicture5.jpeg'),
  49. date: '3月15',
  50. time: '17:45',
  51. chargeStationName: '香港沙頭角農莊',
  52. chargeStationAddress: '香港沙頭角農莊停車場',
  53. distance: '680米',
  54. latitude: 22.53898,
  55. longitude: 114.21319
  56. },
  57. {
  58. imgURL: require('../../assets/dummyStationPicture4.jpeg'),
  59. date: '3月15',
  60. time: '17:45',
  61. chargeStationName: '黃竹坑香葉道充電站',
  62. chargeStationAddress: '黃竹坑香葉道44號地下',
  63. distance: '680米',
  64. latitude: 22.24839,
  65. longitude: 114.16303
  66. }
  67. ];
  68. const SearchResultComponent = () => {
  69. const [region, setRegion] = useState<Region>({
  70. latitude: 22.302711, // Default to Hong Kong coordinates
  71. longitude: 114.177216,
  72. latitudeDelta: 0.01,
  73. longitudeDelta: 0.01
  74. });
  75. const [errorMsg, setErrorMsg] = useState<string | null>(null);
  76. const [searchInput, setSearchInput] = useState<string>('');
  77. const sheetRef = useRef<BottomSheet>(null);
  78. const snapPoints = useMemo(() => ['25%', '65%'], []);
  79. const mapRef = useRef<MapView>(null);
  80. const params = useLocalSearchParams();
  81. const [isLoading, setIsLoading] = useState(true);
  82. const [filteredItems, setFilteredItems] = useState<TabItem[]>([]);
  83. useEffect(() => {
  84. if (params.latitude && params.longitude) {
  85. setRegion({
  86. latitude: parseFloat(params.latitude as string),
  87. longitude: parseFloat(params.longitude as string),
  88. latitudeDelta: 0.01,
  89. longitudeDelta: 0.01
  90. });
  91. } else {
  92. (async () => {
  93. let { status } = await Location.requestForegroundPermissionsAsync();
  94. if (status !== 'granted') {
  95. setErrorMsg('Permission to access location was denied');
  96. return;
  97. }
  98. let myLocation = await Location.getLastKnownPositionAsync({});
  99. if (myLocation) {
  100. setRegion({
  101. latitude: myLocation.coords.latitude,
  102. longitude: myLocation.coords.longitude,
  103. latitudeDelta: 0.01,
  104. longitudeDelta: 0.01
  105. });
  106. }
  107. })();
  108. }
  109. }, []);
  110. useEffect(() => {
  111. if (mapRef.current && region) {
  112. mapRef.current.animateToRegion(region, 1000);
  113. }
  114. }, [region]);
  115. useEffect(() => {
  116. if (searchInput === '') {
  117. setFilteredItems([]);
  118. } else {
  119. const filteredData = dummyTabItems.filter((item) =>
  120. item.chargeStationName.includes(searchInput.toLocaleUpperCase())
  121. );
  122. setFilteredItems(filteredData);
  123. }
  124. }, [searchInput]);
  125. if (errorMsg) {
  126. return (
  127. <View className="flex-1 justify-center items-center ">
  128. <Text className="text-red-500">{errorMsg}</Text>
  129. </View>
  130. );
  131. }
  132. const handleRegionChange = (newRegion: Region) => {
  133. if (mapRef.current) {
  134. mapRef.current.animateToRegion(newRegion, 1000);
  135. }
  136. setRegion(newRegion);
  137. sheetRef.current?.snapToIndex(0);
  138. };
  139. // ************************************************************************************************
  140. const [currentLocation, setCurrentLocation] = useState<Location.LocationObject | null>(null);
  141. const [stations, setStations] = useState([]);
  142. const [tabItems, setTabItems] = useState<TabItem[]>([]);
  143. const getCurrentLocation = async () => {
  144. let { status } = await Location.requestForegroundPermissionsAsync();
  145. if (status !== 'granted') {
  146. console.error('Permission to access location was denied');
  147. return;
  148. }
  149. let location = await Location.getLastKnownPositionAsync({});
  150. setCurrentLocation(location);
  151. };
  152. useEffect(() => {
  153. getCurrentLocation();
  154. }, []);
  155. const fetchStations = async () => {
  156. setIsLoading(true);
  157. const fetchedStations = await chargeStationService.fetchChargeStations();
  158. setStations(fetchedStations);
  159. if (currentLocation) {
  160. const TabItems = await Promise.all(
  161. fetchedStations.map(async (station: any) => {
  162. return {
  163. chargeStationAddress: station.Address,
  164. chargeStationName: station.StationName,
  165. lng: station.StationLng,
  166. lat: station.StationLat,
  167. date: '今天',
  168. stationID: station.StationID,
  169. imgURL: station.image
  170. };
  171. })
  172. );
  173. setTabItems(TabItems);
  174. setIsLoading(false);
  175. }
  176. };
  177. useEffect(() => {
  178. if (currentLocation) {
  179. fetchStations();
  180. }
  181. }, [currentLocation]);
  182. const formatDistance = (distanceInMeters: number): string => {
  183. if (distanceInMeters < 1000) {
  184. return `${Math.round(distanceInMeters)}米`;
  185. } else {
  186. const distanceInKm = distanceInMeters / 1000;
  187. return `${distanceInKm.toFixed(1)}公里`;
  188. }
  189. };
  190. return (
  191. <TouchableWithoutFeedback onPress={Keyboard.dismiss}>
  192. <SafeAreaView className="flex-1" edges={['top', 'left', 'right']}>
  193. <View className="flex-1 relative">
  194. <View
  195. style={{
  196. position: 'absolute',
  197. top: 10,
  198. left: 10,
  199. right: 10,
  200. zIndex: 1,
  201. backgroundColor: 'transparent',
  202. alignItems: 'center'
  203. }}
  204. >
  205. <View className=" flex-1 flex-row bg-white rounded-xl">
  206. <Pressable
  207. style={styles.leftArrowBackButton}
  208. onPress={() => {
  209. if (router.canGoBack()) {
  210. router.back();
  211. } else {
  212. router.replace('/(auth)/(tabs)/(home)');
  213. }
  214. }}
  215. >
  216. <ArrowIconSvg />
  217. </Pressable>
  218. <NormalInput
  219. placeholder="搜尋這裡"
  220. onChangeText={(text) => {
  221. setSearchInput(text);
  222. }}
  223. extendedStyle={styles.textInput}
  224. />
  225. </View>
  226. {filteredItems.length > 0 && (
  227. <View style={styles.dropdown}>
  228. <View>
  229. {filteredItems.map((item, index) => (
  230. <Pressable
  231. key={index}
  232. onPress={() => {
  233. setSearchInput(item.chargeStationName);
  234. setFilteredItems([]);
  235. handleRegionChange({
  236. latitude: item.lat as number,
  237. longitude: item.lng as number,
  238. latitudeDelta: 0.01,
  239. longitudeDelta: 0.01
  240. });
  241. }}
  242. style={({ pressed }) => [
  243. styles.dropdownItem,
  244. pressed && styles.dropdownItemPress
  245. ]}
  246. >
  247. <Text>{item.chargeStationName}</Text>
  248. </Pressable>
  249. ))}
  250. </View>
  251. </View>
  252. )}
  253. </View>
  254. <MapView
  255. ref={mapRef}
  256. provider={PROVIDER_GOOGLE}
  257. style={styles.map}
  258. region={region}
  259. // initialRegion={region}
  260. cameraZoomRange={{
  261. minCenterCoordinateDistance: 500,
  262. maxCenterCoordinateDistance: 90000,
  263. animated: true
  264. }}
  265. showsUserLocation={true}
  266. showsMyLocationButton={false}
  267. >
  268. {tabItems.map((item, index) => (
  269. <Marker
  270. key={index}
  271. coordinate={{
  272. latitude: item.lat as number,
  273. longitude: item.lng as number
  274. }}
  275. title={item.chargeStationName}
  276. description={item.chargeStationAddress}
  277. />
  278. ))}
  279. </MapView>
  280. <BottomSheet ref={sheetRef} index={0} snapPoints={snapPoints}>
  281. <BottomSheetScrollView contentContainerStyle={styles.contentContainer}>
  282. <View className="flex-1 mx-[5%]">
  283. {isLoading ? (
  284. <View className="pt-14">
  285. <ActivityIndicator color="#34657b" />
  286. </View>
  287. ) : (
  288. tabItems
  289. .filter((item) => item.chargeStationName.includes(searchInput.toUpperCase()))
  290. .map((item, index) => {
  291. return (
  292. <Pressable
  293. key={index}
  294. onPress={() => {
  295. handleRegionChange({
  296. latitude: item.lat as number,
  297. longitude: item.lng as number,
  298. latitudeDelta: 0.01,
  299. longitudeDelta: 0.01
  300. });
  301. router.push({
  302. pathname: '/resultDetailPage',
  303. params: {
  304. imageSource: item.imgURL as string,
  305. chargeStationAddress: item.chargeStationAddress,
  306. chargeStationID: item.stationID,
  307. chargeStationName: item.chargeStationName,
  308. stationLat: item.lat,
  309. stationLng: item.lng
  310. }
  311. });
  312. }}
  313. style={({ pressed }) => [
  314. styles.container,
  315. {
  316. backgroundColor: pressed ? '#e7f2f8' : '#ffffff'
  317. }
  318. ]}
  319. >
  320. <View style={styles.rowContainer}>
  321. <Image style={styles.image} source={{ uri: item.imgURL } as ImageSourcePropType} />
  322. <View style={styles.textContainer}>
  323. <Text
  324. style={{
  325. fontWeight: '400',
  326. fontSize: 18,
  327. color: '#222222'
  328. }}
  329. >
  330. {item.chargeStationName}
  331. </Text>
  332. <Text
  333. style={{
  334. fontWeight: '400',
  335. fontSize: 14,
  336. color: '#888888'
  337. }}
  338. >
  339. {item.chargeStationAddress}
  340. </Text>
  341. <View className="flex-row space-x-2 items-center">
  342. <CheckMarkLogoSvg />
  343. <Text
  344. style={{
  345. fontWeight: '400',
  346. fontSize: 14,
  347. color: '#222222'
  348. }}
  349. >
  350. Walk-in
  351. </Text>
  352. </View>
  353. </View>
  354. {/* <Text
  355. style={{
  356. fontWeight: '400',
  357. fontSize: 16,
  358. color: '#888888',
  359. marginTop: 22
  360. }}
  361. className="flex-1 text-right"
  362. >
  363. {item.distance}
  364. </Text> */}
  365. </View>
  366. </Pressable>
  367. );
  368. })
  369. )}
  370. </View>
  371. </BottomSheetScrollView>
  372. </BottomSheet>
  373. </View>
  374. </SafeAreaView>
  375. </TouchableWithoutFeedback>
  376. );
  377. };
  378. export default SearchResultComponent;
  379. const styles = StyleSheet.create({
  380. container: {
  381. flex: 1
  382. },
  383. map: {
  384. flex: 1,
  385. width: '100%',
  386. height: '100%'
  387. },
  388. contentContainer: {
  389. backgroundColor: 'white'
  390. },
  391. itemContainer: {
  392. padding: 6,
  393. margin: 6,
  394. backgroundColor: '#eee'
  395. },
  396. image: {
  397. width: 100,
  398. height: 100,
  399. marginTop: 15,
  400. marginRight: 15,
  401. borderRadius: 10
  402. },
  403. textContainer: { flexDirection: 'column', gap: 8, marginTop: 22 },
  404. rowContainer: { flexDirection: 'row' },
  405. textInput: {
  406. width: '85%',
  407. maxWidth: '100%',
  408. fontSize: 16,
  409. padding: 20,
  410. paddingLeft: 0,
  411. borderLeftWidth: 0,
  412. borderTopWidth: 1,
  413. borderBottomWidth: 1,
  414. borderRightWidth: 1,
  415. borderBottomRightRadius: 12,
  416. borderTopRightRadius: 12,
  417. borderRadius: 0,
  418. borderColor: '#bbbbbb'
  419. },
  420. leftArrowBackButton: {
  421. width: '15%',
  422. maxWidth: '100%',
  423. fontSize: 16,
  424. padding: 20,
  425. paddingLeft: 30,
  426. borderBottomLeftRadius: 12,
  427. borderTopLeftRadius: 12,
  428. borderColor: '#bbbbbb',
  429. borderTopWidth: 1,
  430. borderBottomWidth: 1,
  431. borderLeftWidth: 1,
  432. alignItems: 'center',
  433. justifyContent: 'center'
  434. },
  435. dropdown: {
  436. backgroundColor: 'white',
  437. borderBottomLeftRadius: 12,
  438. borderBottomRightRadius: 12,
  439. borderLeftWidth: 1,
  440. borderRightWidth: 1,
  441. borderBottomWidth: 1,
  442. marginTop: 10,
  443. maxHeight: 200,
  444. width: '100%',
  445. position: 'absolute',
  446. top: 50,
  447. zIndex: 2,
  448. borderColor: '#bbbbbb'
  449. },
  450. dropdownItem: {
  451. padding: 10,
  452. borderBottomWidth: 1,
  453. borderBottomColor: '#ddd'
  454. },
  455. dropdownItemPress: {
  456. backgroundColor: '#e8f8fc'
  457. }
  458. });