google-map-react marker not showing - reactjs

hi all im trying to implement google maps in react.js , the map is showing fine however when i try to show my marker , nothing is being displayed. IF i remove lat and long values then marker will show up on top of the map. But if i add lat and long values to it , then it stops showing. Can someone please help?
import React, { Component } from 'react';
import GoogleMapReact from 'google-map-react';
import marker from './marker.png';
import { geolocated } from 'react-geolocated';
const AnyReactComponent = ({ text }) => (
<div>
<img src={marker} style={{ height: '50px', width: '50px' }} />
</div>
);
export default class Map extends Component {
static defaultProps = {
zoom: 11,
};
Componentwillmount() {
console.log(this.props.center.latitude);
}
render() {
return (
<div className="google-map" style={{ width: '100%', height: '2000px', backgroundColor: 'red' }}>
<GoogleMapReact
options={{
styles:ExampleMapStyles
}}
center={this.props.center} defaultZoom={this.props.zoom}>
<AnyReactComponent
lat={59.955413}
lng={30.337844}
text={'Kreyser Avrora'}
/>
</GoogleMapReact>
</div>
);
}
}

The documentation shows that you can use<AnyReactCompenent/> which you can use if you want to have your own Marker or text. However, if you wish to use the default marker then you would have to pass as a property into the <GoogleMapReact></GoogleMapReact> component. The docs mention 'You can access Google Maps map and maps objects by using onGoogleApiLoaded, in this case, you will need to set yesIWantToUseGoogleMapApiInternals to true'. This just means add the name of the property without passing a value to it as I have in mine. It may not be entirely clear from the description in the Readme, but the maps argument is, in fact, the maps API object (and map is, of course, the current Google Map instance). Therefore, you should pass both into the method with the renderMarkers = (map, maps) => {} function.
You can try this:
import React, { Fragment } from 'react';
import GoogleMapReact from 'google-map-react';
const GoogleMaps = ({ latitude, longitude }) => {
const renderMarkers = (map, maps) => {
let marker = new maps.Marker({
position: { lat: latitude, lng: longitude },
map,
title: 'Hello World!'
});
return marker;
};
return (
<Fragment>
<div style={{ height: '50vh', width: '100%' }}>
<GoogleMapReact
bootstrapURLKeys={{ key: 'YOUR KEY' }}
defaultCenter={{ lat: latitude, lng: longitude }}
defaultZoom={16}
yesIWantToUseGoogleMapApiInternals
onGoogleApiLoaded={({ map, maps }) => renderMarkers(map, maps)}
>
</GoogleMapReact>
</div>
</Fragment>
);
};
export default GoogleMaps;

I think the main question that you need to answer is: What are your center props?
I used your code in sandbox and did a some small adaption: I used the same lat/longitude where your marker should be rendered in order to see at a glance whether it is actually shown. And it is:
https://codesandbox.io/s/00p1ry2v0v
export default class Map extends Component {
static defaultProps = {
zoom: 11,
center: {
lat: 49.955413,
lng: 30.337844
}
};
render() {
const mapStyles = {
width: "100%",
height: "100%"
};
return (
<div
className="google-map"
style={{ width: "100%", height: "2000px", backgroundColor: "red" }}
>
<GoogleMapReact
style={mapStyles}
center={this.props.center}
defaultZoom={this.props.zoom}
>
<AnyReactComponent
lat={49.955413}
lng={30.337844}
text={"Kreyser Avrora"}
/>
</GoogleMapReact>
</div>
);
}
}
So, make sure you start the map with a proper initial center position. :)

Related

React Google Maps not opening on specified lat, long, but in random place

This is the code for the maps component. Any ideas why it doesn't open straight on those coordinates? Is there another prop that I didn't set on true?
import React, { Component } from 'react';
import GoogleMapReact from 'google-map-react';
const AnyReactComponent = ({ text }) => <div>{text}</div>;
class SimpleMap extends Component {
static defaultProps = {
center: {
lat: 59.95,
lng: 30.33
},
zoom: 11,
yesIWantToUseGoogleMapApiInternals: true
};
render() {
return (
<div style={{ height: '50vh', width: '35%', justifyContent: 'flex-end' }}>
<GoogleMapReact
bootstrapURLKeys={{ key:"my key" }}
defaultCenter={this.props.center}
defaultZoom={this.props.zoom}
yesIWantToUseGoogleMapApiInternals
lat={45.756659}
lng={21.228703}
>
<AnyReactComponent
lat={45.756659}
lng={21.228703}
text="Service Location"
/>
</GoogleMapReact>
</div>
);
}
}
I believe what you are asking is this:
Why isn't the map moving to the new marker location?
If this is what you are asking, it is because you aren't changing your center coords, and so it stays where you originally set it.
Checkout this code sandbox where I set the center value using a ternary expression to the new location, and the map goes to where the marker is.
https://codesandbox.io/s/wonderful-cdn-nqizf?file=/src/App.js:1177-1204
you'll want to actually set it using state in a real project. But this for proof of concept.

How to call a function if Current position within Polygon in google-,maps-react?

I am implementing google-maps-react. I need functinality if user current location is in the polygon, I need to enable a button. I searched for containslocation() but didn't get appropriate answer. Here is my code:
import { Map, GoogleApiWrapper, InfoWindow, Marker, Polygon } from 'google-maps-react';
...
...
<CurrentLocation
centerAroundCurrentLocation
google={this.props.google}
>
<Polygon
paths={triangleCoords}
strokeColor="#0000FF"
strokeOpacity={0.8}
strokeWeight={2}
fillColor="#0000FF"
fillOpacity={0.35} />
<Marker
position={{ lat: this.state.currentPosition.lat, lng: this.state.currentPosition.lng }}
onClick={this.onMarkerClick}
name={'Current Location'}
/>
<InfoWindow
marker={this.state.activeMarker}
visible={this.state.showingInfoWindow}
onClose={this.onClose}
>
<div>
<h4>{this.state.selectedPlace.name}</h4>
</div>
</InfoWindow>
</CurrentLocation>
Hereś how you can implement it using google-maps-react library:
You need to have a function everytime the map is ready onReady. This function will fetch the current position.
You can use the HTML5 Geolocation feature to get the current location of the user.
You need to import the useRef from React so that you can use ref to get your polygon object.
Once you have the coordinate of the user and the polygon object, you need to use google.maps.geometry.poly.containsLocation to check if the polygon contains the coordinate.
You need to also import useState to manipulate state variables. You will need this as a flag to determine if the coordinate is contained by the polygon or not and will also be used in the condition when showing the button.
So to show the button html you then use the state variable we set and check if it is set to true, then a button should be shown.
Here's the code snippet for the working code:
import React, { useRef, useState } from "react";
import { Map, GoogleApiWrapper, Polygon } from "google-maps-react";
function MapContainer(props) {
const refPoly = useRef(null);
const style = {
position: "absolute",
width: "400px",
height: "800px"
};
const containerStyle = {
position: "absolute",
width: "800px",
height: "400px"
};
const [showBtn, setShowBtn] = useState(null);
const triangleCoords = [
{ lat: 25.774, lng: -80.19 },
{ lat: 18.466, lng: -66.118 },
{ lat: 32.321, lng: -64.757 }
];
const fetchCurrentPosition = () => {
navigator.geolocation.getCurrentPosition(
function(position) {
var pos = new google.maps.LatLng(
position.coords.latitude,
position.coords.longitude
);
console.log(position.coords);
google.maps.geometry.poly.containsLocation(pos, refPoly.current.polygon)
? setShowBtn(true)
: setShowBtn(false);
},
function(error) {
console.log(error);
}
);
};
return (
<div>
{showBtn === true && (
<button display="block" type="button">
Showing Button!
</button>
)}
<div>
<Map
className="map"
style={style}
containerStyle={containerStyle}
google={props.google}
onReady={fetchCurrentPosition}
initialCenter={{
lat: 25.774,
lng: -80.19
}}
style={{ height: "100%", position: "relative", width: "100%" }}
zoom={3}
>
<Polygon
ref={refPoly}
paths={triangleCoords}
strokeColor="#0000FF"
strokeOpacity={0.8}
strokeWeight={2}
fillColor="#0000FF"
fillOpacity={0.35}
/>
</Map>
</div>
</div>
);
}
export default GoogleApiWrapper({
apiKey: "YOUR_API_KEY",
libraries: ["geometry"]
})(MapContainer);
Note: To show the button, change the path value of your polygon around your area so that the condition will be set to true. Also use your own API key to make the code work properly. Here's the working code.

Setting a dynamic center with google map's api

class SimpleMap extends Component {
constructor(props) {
super(props);
}
static defaultProps = {
center: {lat: 40.73, lng: -73.93},
zoom: 12
}
render() {
return (
<div style={{ height: '100vh', width: '100%' }}>
<GoogleMapReact
bootstrapURLKeys={{ key: API_KEY}}
defaultCenter={this.props.center}
defaultZoom={5}
>
<AnyReactComponent
lat={this.props.lat}
lng={this.props.long}
text=" the ISS"
/>
</GoogleMapReact>
</div>
);
}
}
export default SimpleMap;
I have a location being supplied by an API that I wish to display on google maps by centring onto the long and lat coordinates that I have on the parent. when I change the static defaultProps to use props 'this.props.lat/long' it won't render the map unless I hard code my lat and long.
any advice would be appreciated

Why react-google-maps rendering one Circle component twice?

When I added react-google-maps to project, render worked twice. So I have 2 circles one under another. Also, I display the center coordinates by onDragEnd() method. This event works for only one of this circles.
Any others google maps dosen`t exist on project.
Here is some ways I was trying to fix it:
1) Use only withGoogleMap,
2) Use GoogleMapsWrapper component inside render() method of parent component,
3) Use componentDidMount();
trying everything from satckoverflow :)
and nothing helps.
import React, { Component } from 'react';
import MapForm from './mapForm';
import { GoogleMap, withGoogleMap, withScriptjs, Circle } from 'react-google-maps';
const GoogleMapsWrapper = withScriptjs(withGoogleMap(props => {
const {onMapMounted, ...otherProps} = props;
return <GoogleMap {...otherProps} ref={c => {
onMapMounted && onMapMounted(c)
}}>{props.children}</GoogleMap>
}));
class GoogleMapsContainer extends Component {
state = {
coords: {lat:0, lng: 0}
};
dragCircle = () => {
this.setState({
coords: {
lat: this._circle.getCenter().lat(),
lng: this._circle.getCenter().lng()
}
})
}
render() {
return(
<div style={{display: 'flex',flexDirection: 'row', width: '100%', marginLeft: '37px'}}>
<MapForm
filters={this.props.filters}
coords={this.state.coords}
/>
<GoogleMapsWrapper
googleMapURL={`https://maps.googleapis.com/maps/api/js?key=${KEY}&v=3.exp&libraries=geometry,drawing,places`}
loadingElement={<div style={{height: `100%`}}/>}
containerElement={<div style={{position: 'relative',width: '100%', }} />}
mapElement={<div style={{height: `100%`}}/>}
defaultZoom={13}
defaultCenter={KYIV}
>
<Circle
ref={(circle) => {this._circle = circle}}
defaultCenter = {KYIV}
defaultDraggable={true}
defaultEditable={true}
defaultRadius={2000}
onDragEnd = {this.dragCircle}
options={{
strokeColor: `${colors.vividblue}`,
fillColor: `${colors.vividblue}`,
fillOpacity: 0.1
}}
/>
</GoogleMapsWrapper>
</div>
)
}
}
export default GoogleMapsContainer;
I need only one circle with my methods.mycircles
Ok, the problem was in React StrictMode component in project.

Google Maps with ReactJS not loading

Please help. I am trying to load a map using my API KEY.
The problem is that neither map nor props are loading. Probably I'm missing the point.
Any ideas?
Here's the repo
And here's the Map Container's code
import React, { Component } from 'react';
import {GoogleApiWrapper, Map} from 'google-maps-react';
const API_KEY = 'apikeystring';
export class Container extends Component {
render() {
const style = {
width: '200px',
height: '200px'
}
if (!this.props.loaded) {
return <div>Loading props...</div>
}
return (
<div style={style}>
<Map
google={window.google}
initialCenter={{
lat: 44.498955,
lng: 11.327591
}}
style={{
width: '100px',
height: '100px'
}}
/>
</div>
)
}
}
export default GoogleApiWrapper({
apiKey: (API_KEY)
})(Container)
What am I doing wrong?
In order to show your Loading props, you have to do it like this:
return (
<div style={style}>
{(!this.props.loaded) ? <div>Loading props...</div> : null}
<Map
google={window.google}
initialCenter={
lat: 44.498955,
lng: 11.327591
}
style={{
width: '100px',
height: '100px'
}}
/>
</div>
I’m not sure but I don’t think you need double courly braces for initialCenter, hope it helps.

Resources