Setting a dynamic center with google map's api - reactjs

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

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.

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-map-react marker not showing

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. :)

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.

React leaflet marker layer not updating on zoom

The react-leaflet-marker-layer does not update on zooming the map in/out.
It stays the same, while the map content changes its zoom level.
This happens both during zoom using mouse scroll and the +/- buttons.
NOTE: This may be related, I noticed the map rendering is very slow and some tiles take very long to load. Zooming in/out helps to load them instantly.
import React from 'react';
import ReactDOM from 'react-dom';
import { Map, Marker, Popup, TileLayer } from 'react-leaflet';
import MarkerLayer from 'react-leaflet-marker-layer';
const position = { lng: -122.673447, lat: 45.522558 };
const markers = [
{
position: { lng: -122.67344700000, lat: 45.522558100000 },
text: 'Voodoo Doughnut',
},
{
position: { lng: -122.67814460000, lat: 45.5225512000000 },
text: 'Bailey\'s Taproom',
},
{
position: { lng: -122.67535700000002, lat: 45.5192743000000 },
text: 'Barista'
},
{
position: { lng: -122.65596570000001, lat: 45.5199148000001 },
text: 'Base Camp Brewing'
}
];
class ExampleMarkerComponent extends React.Component {
render() {
const style = {
border: 'solid 1px lightblue',
backgroundColor: '#333333',
borderRadius: '50%',
marginTop: '-5px',
marginLeft: '-5px',
width: '10px',
height: '10px'
};
return (
<div style={Object.assign({}, this.props.style, style)}></div>
);
}
}
class MapView extends React.Component {
render() {
return (
<div
style={{
height:"700px"
}}>
<Map center={position} zoom={13}
style={{
height:"700px"
}}>
<TileLayer
url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
attribution='© OpenStreetMap contributors'
/>
<MarkerLayer
markers={markers}
longitudeExtractor={m => m.position.lng}
latitudeExtractor={m => m.position.lat}
markerComponent={ExampleMarkerComponent} />
</Map>
</div>
);
}
}
module.exports = MapView;
I also encountered this issue. Seems like the developer didn't add some event hadlers dor these casese. Not sure if this was intended, but looks more like a bug. The module version at this moment is 0.0.3, so I would't expect much from it.
You can actually just override the method, that sets the event handlers for the layer.
class MarkerLayer extends MapLayer {
attachEvents () {
const map = this.props.map;
map.on('viewreset', () => this.updatePosition());
map.on('zoom', () => this.updatePosition());
map.on('zoomlevelschange', () => this.updatePosition());
}
}
Now, if you use MarkerLayer class, markers would saty where they belong

Resources