@@ -6,13 +6,21 @@ interface IMap {
6
6
mapTypeControl ?: boolean ;
7
7
}
8
8
9
+ interface IMarker {
10
+ address : string ;
11
+ latitude : number ;
12
+ longitude : number ;
13
+ }
14
+
9
15
type GoogleLatLng = google . maps . LatLng ;
10
16
type GoogleMap = google . maps . Map ;
17
+ type GoogleMarker = google . maps . Marker ;
11
18
12
19
const Map : React . FC < IMap > = ( { mapType, mapTypeControl = false } ) => {
13
20
14
21
const ref = useRef < HTMLDivElement > ( null ) ;
15
22
const [ map , setMap ] = useState < GoogleMap > ( ) ;
23
+ const [ marker , setMarker ] = useState < IMarker > ( ) ;
16
24
17
25
const startMap = ( ) : void => {
18
26
if ( ! map ) {
@@ -26,6 +34,54 @@ const Map: React.FC<IMap> = ({ mapType, mapTypeControl = false}) => {
26
34
initMap ( 4 , defaultAddress ) ;
27
35
} ;
28
36
37
+ const initEventListener = ( ) :void => {
38
+ if ( map ) {
39
+ google . maps . event . addListener ( map , 'click' , function ( e ) {
40
+ coordinateToAddress ( e . latLng ) ;
41
+ } )
42
+ }
43
+ } ;
44
+ useEffect ( initEventListener , [ map ] ) ;
45
+
46
+ const coordinateToAddress = async ( coordinate : GoogleLatLng ) => {
47
+ const geocoder = new google . maps . Geocoder ( ) ;
48
+ await geocoder . geocode ( { location : coordinate } , function ( results , status ) {
49
+ if ( status === 'OK' ) {
50
+ setMarker ( {
51
+ address : results [ 0 ] . formatted_address ,
52
+ latitude : coordinate . lat ( ) ,
53
+ longitude : coordinate . lng ( )
54
+ } )
55
+ }
56
+ } ) ;
57
+ } ;
58
+
59
+ const addSingleMarker = ( ) :void => {
60
+ if ( marker ) {
61
+ addMarker ( new google . maps . LatLng ( marker . latitude , marker . longitude ) ) ;
62
+ }
63
+ } ;
64
+ useEffect ( addSingleMarker , [ marker ] ) ;
65
+
66
+ const addMarker = ( location : GoogleLatLng ) : void => {
67
+ const marker :GoogleMarker = new google . maps . Marker ( {
68
+ position : location ,
69
+ map : map ,
70
+ icon : getIconAttributes ( '#000000' )
71
+ } ) ;
72
+ } ;
73
+
74
+ const getIconAttributes = ( iconColor : string ) => {
75
+ return {
76
+ path : 'M11.0639 15.3003L26.3642 2.47559e-05L41.6646 15.3003L26.3638 51.3639L11.0639 15.3003 M22,17.5a4.5,4.5 0 1,0 9,0a4.5,4.5 0 1,0 -9,0Z' ,
77
+ fillColor : iconColor ,
78
+ fillOpacity : 0.8 ,
79
+ strokeColor : 'pink' ,
80
+ strokeWeight : 2 ,
81
+ anchor : new google . maps . Point ( 30 , 50 )
82
+ } ;
83
+ } ;
84
+
29
85
const initMap = ( zoomLevel : number , address : GoogleLatLng ) : void => {
30
86
if ( ref . current ) {
31
87
setMap (
0 commit comments