1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
|
import React, { useState, useCallback, useRef, useEffect } from 'react';
import {
GoogleMap,
useJsApiLoader,
Marker,
Autocomplete,
} from '@react-google-maps/api';
import { useMaps } from '../stores/useMaps';
import { LocateFixed, MapPinIcon } from 'lucide-react';
import { Button } from '@chakra-ui/react';
const containerStyle = {
width: '100%',
height: '400px',
};
const PinpointLocation = ({
initialLatitude,
initialLongitude,
initialAddress,
}) => {
const { isLoaded } = useJsApiLoader({
googleMapsApiKey: process.env.NEXT_PUBLIC_GOOGLE_API_KEY,
libraries: ['places'],
});
const {
setAddressMaps,
selectedPosition,
setSelectedPosition,
setDetailAddress,
setPinedMaps,
getDefaultCenter, // ✅ ambil default center dari store
} = useMaps();
const [tempAddress, setTempAddress] = useState(initialAddress || '');
const [tempPosition, setTempPosition] = useState(
initialLatitude && initialLongitude
? { lat: parseFloat(initialLatitude), lng: parseFloat(initialLongitude) }
: selectedPosition?.lat && selectedPosition?.lng
? selectedPosition
: getDefaultCenter() // ✅ fallback aman untuk view
);
const [markerIcon, setMarkerIcon] = useState(null);
const autocompleteRef = useRef(null);
useEffect(() => {
if (isLoaded && window.google) {
setMarkerIcon({
url: 'https://cdn.pixabay.com/photo/2014/04/03/10/03/google-309740_1280.png',
scaledSize: new window.google.maps.Size(25, 40),
});
}
// Jika ada koordinat awal tapi belum ada address → reverse geocode
if (initialLatitude && initialLongitude && !initialAddress) {
getAddress(parseFloat(initialLatitude), parseFloat(initialLongitude));
}
}, [isLoaded, initialLatitude, initialLongitude, initialAddress]);
const getAddressComponent = (components, type) => {
const component = components.find((comp) => comp.types.includes(type));
return component ? component.long_name : '';
};
// fill from pin point
const getAddress = async (lat, lng) => {
try {
const response = await fetch(
`https://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${lng}&key=${process.env.NEXT_PUBLIC_GOOGLE_API_KEY}`
);
const data = await response.json();
if (data.results[0]) {
const addressComponents = data.results[0].address_components;
const formattedAddress = data.results[0].formatted_address;
const details = {
// street:
// getAddressComponent(addressComponents, 'route') +
// ' ' +
// getAddressComponent(addressComponents, 'street_number'),
province: getAddressComponent(
addressComponents,
'administrative_area_level_1'
),
district: getAddressComponent(
addressComponents,
'administrative_area_level_2'
),
subDistrict: getAddressComponent(
addressComponents,
'administrative_area_level_3'
),
village: getAddressComponent(
addressComponents,
'administrative_area_level_4'
),
postalCode: getAddressComponent(addressComponents, 'postal_code'),
};
setDetailAddress(details);
setTempAddress(formattedAddress);
}
} catch (error) {
console.error('Error fetching address:', error);
}
};
const onMapClick = useCallback((event) => {
const lat = event.latLng.lat();
const lng = event.latLng.lng();
const newPosition = { lat, lng };
setTempPosition(newPosition);
getAddress(lat, lng);
}, []);
const handlePlaceSelect = () => {
const place = autocompleteRef.current.getPlace();
if (place && place.geometry) {
const lat = place.geometry.location.lat();
const lng = place.geometry.location.lng();
const newPosition = { lat, lng };
setTempPosition(newPosition);
setTempAddress(place.formatted_address);
getAddress(lat, lng);
}
};
const handleUseCurrentLocation = () => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
(position) => {
const lat = position.coords.latitude;
const lng = position.coords.longitude;
const newPosition = { lat, lng };
setTempPosition(newPosition);
getAddress(lat, lng);
},
(error) => {
console.error('Error getting current location:', error);
}
);
}
};
const handleSavePinpoint = (event) => {
event.preventDefault();
// ✅ cegah save jika masih di default center (user belum benar2 pilih lokasi)
const dc = getDefaultCenter();
const isDefault =
Math.abs(tempPosition.lat - dc.lat) < 1e-6 &&
Math.abs(tempPosition.lng - dc.lng) < 1e-6;
if (!tempAddress || isDefault) {
alert('Silahkan pilih lokasi di peta atau autocomplete terlebih dahulu');
return;
}
setSelectedPosition(tempPosition);
setAddressMaps(tempAddress);
setPinedMaps(false);
};
return (
<div className='w-full'>
<h3>Tentukan Pinpoint Lokasi</h3>
<div style={{ marginBottom: '10px' }}>
{isLoaded ? (
<Autocomplete
onLoad={(ref) => (autocompleteRef.current = ref)}
onPlaceChanged={handlePlaceSelect}
>
<input
type='text'
placeholder='Cari Alamat...'
value={tempAddress}
onChange={(e) => setTempAddress(e.target.value)}
style={{ width: '100%', padding: '8px' }}
/>
</Autocomplete>
) : (
<p>Loading autocomplete...</p>
)}
</div>
<div>
{isLoaded ? (
<GoogleMap
mapContainerStyle={containerStyle}
center={tempPosition || getDefaultCenter()} // ✅ aman jika null
zoom={15}
onClick={onMapClick}
>
{markerIcon && (
<Marker
position={tempPosition || getDefaultCenter()} // ✅ selalu ada posisi
draggable={true}
onDragEnd={(e) => {
const lat = e.latLng.lat();
const lng = e.latLng.lng();
const newPosition = { lat, lng };
setTempPosition(newPosition);
getAddress(lat, lng);
}}
icon={markerIcon}
/>
)}
</GoogleMap>
) : (
<p>Loading map...</p>
)}
</div>
<div style={{ marginTop: '20px' }}>
<Button variant='solid' onClick={handleUseCurrentLocation}>
<LocateFixed className='h-6 w-6 text-gray-500 mr-2' /> Gunakan Lokasi
Saat Ini
</Button>
</div>
<div style={{ marginTop: '10px' }}>
<p>PinPoint :</p>
<div className='flex gap-x-2 shadow-md rounded-sm text-gray-500 p-3 items-center'>
<MapPinIcon className='h-8 w-8 text-gray-500 mr-3' />
<label>{tempAddress || 'Pilih lokasi di peta'}</label>
</div>
</div>
<div className='mt-6 flex justify-end'>
<button
className='p-3 border border-red-500 bg-red-600 text-white font-semibold rounded-lg'
onClick={handleSavePinpoint}
>
Simpan Lokasi Ini
</button>
</div>
</div>
);
};
export default PinpointLocation;
|