'Google maps react marker not showing
Im new in react I've tried to use google maps, I want to get latlng by click on map and showing the marker I found and have tried [this][1]
it work, I can choose the location that I want and get latlng by click on map, but the marker is not showing
here's my code
async componentDidMount() {
const { lat, lng } = await this.getcurrentLocation();
this.setState(prev => ({
fields: {
...prev.fields,
location: {
lat,
lng
}
},
currentLocation: {
lat,
lng
}
}));
}
getcurrentLocation() {
if (navigator && navigator.geolocation) {
return new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition(pos => {
const coords = pos.coords;
resolve({
lat: coords.latitude,
lng: coords.longitude
});
});
});
}
return {
lat: 0,
lng: 0
};
}
addMarker = (location, map) => {
this.setState(prev => ({
fields: {
...prev.fields,
location
}
}));
map.panTo(location);
alert(location);
};
in render
<Map
google={this.props.google}
style={{
width: "auto",
height: "300px",
position: "relative"
}}
onClick={(t, map, c) => this.addMarker(c.latLng, map)}
zoom={14}
>
{(marker => {
return <Marker position={this.state.fields.location}
/>
})};
Map>
thanks
Solution 1:[1]
<Marker
title={'The marker`s title will appear as a tooltip.'}
name={'SOMA'}
position={{lat: 37.778519, lng: -122.405640}} />
Add this code manually and check if Marker is working or not. Please double check if you are getting lat and lng by console.log()
Solution 2:[2]
Use conditional rendering to render marker component, for example:
{this.state.fields.location && <Marker position={this.state.fields.location}/>}
or
{
this.state.fields.location ?
<Marker position={this.state.fields.location}/> : null
}
Solution 3:[3]
For me, the problem was in how I was conditionally adding the markers.
In the markers' icons definitions, I use google.maps methods, so there is a need to wait till the map will be completely loaded. When I was using the direct setState method, the Marker component will never render:
<GoogleMap
...
onLoad={(map) => setMapInstance(map)}
>
{mapInstance && <Marker position={...} icon={...} />}
</GoogleMap>
But when I used the setTimeout to set the instance up: onLoad={(map) => setTimeout(() => setMapInstance(map))}, everything worked as a charm
Full example:
<GoogleMap
...
onLoad={(map) => setTimeout(() => setMapInstance(map))}
>
{mapInstance && (
<Marker
position={location}
icon={{
url: markerUrl,
scaledSize: new google.maps.Size(markerSize, markerSize),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(markerSize / 2, markerSize / 2),
}}
/>
)}
</GoogleMap>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Manzurul Hoque Rumi |
| Solution 2 | Vadim Gremyachev |
| Solution 3 | Oleksandr Danylchenko |
