Reputation: 645
I am using react-google-maps component to make map with one marker. I did it and it is working perfectly, but the problem is that I want that marker will be always centered.
I did research on google, and find out several solutions: one is by google API, but I don't get it how to implement to react-google-maps, and second - add fake marker over map - which I think isn't good solution.
import React from 'react';
import { GoogleMap, withScriptjs, withGoogleMap, Marker} from 'react-google-maps';
function Map() {
return(
<GoogleMap
defaultZoom={13}
defaultCenter={{lat:54.68916, lng:25.2798}}
>
<Marker
position={{lat:54.68916, lng:25.2798}}
draggable={true}
onDragEnd={(e) => markerDrop(e)}
/>
</GoogleMap>
);
}
function markerDrop(event){
//get values of marker
let lat = event.latLng.lat();
let lng = event.latLng.lng();
//insert values to forms
document.getElementById('location_latitude').value = lat;
document.getElementById('location_longitude').value = lng;
return
}
const WrappedMap = withScriptjs(withGoogleMap(Map));
export default function PickLocation(){
return(
<div>
<WrappedMap
googleMapURL={'https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry,drawing,places&key=AIzaSy'}
loadingElement={<div style={{ height: `100%` }} />}
containerElement={<div style={{ height: `400px` }} />}
mapElement={<div style={{ height: `100%` }} />}
/>
</div>
)
}
At the and result have to be similar as uber pick up map, where marker is in the middle of the map, and map is moving around.
Upvotes: 2
Views: 10738
Reputation: 59358
Here is the list of changes to keep marker centered on map move:
1) introduce center
state to keep marker position:
const [center, setCenter] = useState(null);
2) on map move (via bounds_changed
or drag
event listener ) update current center
:
const handleBoundsChanged = () => {
const mapCenter = refMap.current.getCenter(); //get map center
setCenter(mapCenter);
};
where
<GoogleMap
ref={refMap}
onBoundsChanged={handleBoundsChanged}
...
/>
3) position marker by passing center
state:
<Marker position={center} />
Example
function Map() {
const [center, setCenter] = useState({ lat: 54.68916, lng: 25.2798 });
const refMap = useRef(null);
const handleBoundsChanged = () => {
const mapCenter = refMap.current.getCenter(); //get map center
setCenter(mapCenter);
};
return (
<GoogleMap
ref={refMap}
defaultZoom={13}
defaultCenter={{ lat: 54.68916, lng: 25.2798 }}
onBoundsChanged={useCallback(handleBoundsChanged)}
>
<Marker position={center} />
</GoogleMap>
);
}
Note: due to the usage of Hooks React version
16.8
or above is required
Upvotes: 9