1
1
import React , { useState } from "react" ;
2
- import { GoogleMap , InfoWindow , LoadScript , Marker } from "@react-google-maps/api" ;
2
+ import { GoogleMap , InfoWindow , Marker , useJsApiLoader } from "@react-google-maps/api" ;
3
3
4
4
const MapComponent = ( ) => {
5
+
6
+ const { isLoaded, loadError } = useJsApiLoader ( {
7
+ googleMapsApiKey : process . env . REACT_APP_GOOGLE_API_KEY
8
+ } ) ;
9
+
5
10
const initialMarkers = [
6
11
{
7
12
position : {
@@ -29,7 +34,7 @@ const MapComponent = () => {
29
34
} ,
30
35
] ;
31
36
32
- const [ activeInfoWindow , setActiveInfoWindow ] = useState ( "" ) ;
37
+ const [ activeInfoWindow , setActiveInfoWindow ] = useState ( null ) ;
33
38
const [ markers , setMarkers ] = useState ( initialMarkers ) ;
34
39
35
40
const containerStyle = {
@@ -52,38 +57,40 @@ const MapComponent = () => {
52
57
}
53
58
54
59
const markerDragEnd = ( event , index ) => {
55
- console . log ( event . latLng . lat ( ) )
56
- console . log ( event . latLng . lng ( ) )
60
+ console . log ( event . latLng . lat ( ) , event . latLng . lng ( ) )
57
61
}
58
62
59
63
return (
60
- < LoadScript googleMapsApiKey = { process . env . REACT_APP_GOOGLE_API_KEY } >
61
- < GoogleMap
62
- mapContainerStyle = { containerStyle }
63
- center = { center }
64
- zoom = { 15 }
65
- onClick = { mapClicked }
66
- >
67
- { markers . map ( ( marker , index ) => (
68
- < Marker
69
- key = { index }
70
- position = { marker . position }
71
- label = { marker . label }
72
- draggable = { marker . draggable }
73
- onDragEnd = { event => markerDragEnd ( event , index ) }
74
- onClick = { event => markerClicked ( marker , index ) }
75
- >
76
- {
77
- ( activeInfoWindow === index )
78
- &&
79
- < InfoWindow position = { marker . position } >
80
- < b > { marker . position . lat } , { marker . position . lng } </ b >
81
- </ InfoWindow >
82
- }
83
- </ Marker >
84
- ) ) }
85
- </ GoogleMap >
86
- </ LoadScript >
64
+ isLoaded
65
+ &&
66
+ < GoogleMap
67
+ mapContainerStyle = { containerStyle }
68
+ center = { center }
69
+ zoom = { 15 }
70
+ onClick = { mapClicked }
71
+ >
72
+ { markers . map ( ( marker , index ) => (
73
+ < Marker
74
+ key = { index }
75
+ position = { marker . position }
76
+ label = { marker . label }
77
+ draggable = { marker . draggable }
78
+ onDragEnd = { event => markerDragEnd ( event , index ) }
79
+ onClick = { event => markerClicked ( marker , index ) }
80
+ >
81
+ {
82
+ ( activeInfoWindow === index )
83
+ &&
84
+ < InfoWindow
85
+ position = { marker . position }
86
+ onCloseClick = { ( ) => setActiveInfoWindow ( null ) }
87
+ >
88
+ < b > { marker . position . lat } , { marker . position . lng } </ b >
89
+ </ InfoWindow >
90
+ }
91
+ </ Marker >
92
+ ) ) }
93
+ </ GoogleMap >
87
94
) ;
88
95
} ;
89
96
0 commit comments