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.
Related
I am new to React Google Maps. I'm unable to get radius value from Circle.
https://github.com/JustFly1984/react-google-maps-api
I want to get circle redius onRadiusChanged event.
index.js
import React, { Component } from 'react';
import { render } from 'react-dom';
import Map from './Map';
import './style.css';
const App = () => {
return (
<div>
<Map
googleMapURL="https://maps.googleapis.com/maps/api/js?key=AIzaSyDurZQBXjtSzKeieXwtFeGe-jhZu-HEGQU&libraries=drawing"
loadingElement={<div style={{ height: `100%` }} />}
containerElement={<div style={{ height: `400px` }} />}
mapElement={<div style={{ height: `100%` }} />}
center={{ lat: -33.8665433, lng: 151.1956316 }}
zoom={15}
/>
</div>
);
};
render(<App />, document.getElementById('root'));
map.js
import React, { Component } from "react";
import {
withScriptjs,
withGoogleMap,
GoogleMap,
Marker,
Circle
} from "react-google-maps";
class MyMapComponent extends Component {
constructor(props) {
super(props);
this.state = {
radius: 50
}
}
updateRadius(e) {
console.log(e);
}
render() {
return (
<GoogleMap
defaultZoom={this.props.zoom}
defaultCenter={this.props.center}
>
<Marker google={this.props.google}
name={'Dolores park'}
draggable={true}
onDragEnd={this.onMarkerDragEnd}
position={this.props.center}
/>
<Circle
center={this.props.center}
options={{
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 1,
fillColor: "#FF0000",
fillOpacity: 0.35,
clickable: false,
draggable: false,
editable: true,
visible: true,
radius: this.state.radius, //Calculation in Meter
zIndex: 1
}}
onRadiusChanged={this.updateRadius}
/>
</GoogleMap>
);
}
}
export default withScriptjs(withGoogleMap(MyMapComponent));
Result -
undefined
onRadiusChanged (as the underlying center_changed event for a Circle class ) event does not accept any arguments. Since onRadiusChanged event handler method is not bound with its component instance in your example, the updated radius could be determined like this:
updateRadius() {
const updatedRadius = this.getRadius();
}
where this refers to native Circle object.
I create a marker like this:
import React from "react";
import config from 'config';
import { compose, withProps, withState, lifecycle } from "recompose";
import {
withScriptjs,
withGoogleMap,
GoogleMap,
Marker,
DirectionsRenderer,
Polyline,
} from "react-google-maps";
const googleApiKey = config.googleApiKey;
const HistoryView = compose(
withProps({
googleMapURL: `https://maps.googleapis.com/maps/api/js?key=${googleApiKey}&v=3.exp&libraries=geometry,drawing,places`,
loadingElement: <div style={{ height: `100%` }} />,
containerElement: <div style={{ height: `345px` }} />,
mapElement: <div style={{ height: `100%` }} />,
}),
withState('zoom', 'onZoomChange', 11),
withScriptjs,
withGoogleMap,
lifecycle({
componentDidMount() {
const { historyCords } = this.props;
},
componentWillMount() {
this.setState({
zoomToMarkers: map => {
//console.log("Zoom to markers");
const bounds = new google.maps.LatLngBounds();
map.props.children.forEach((child) => {
if (child.type === Marker) {
bounds.extend(new google.maps.LatLng(child.props.position.lat, child.props.position.lng));
}
})
map.fitBounds(bounds);
}
})
},
})
)(props =>
<GoogleMap
//ref={props.zoomToMarkers}
defaultZoom={8}
defaultCenter={new google.maps.LatLng(props.historyCords[0].latitude, props.historyCords[0].longitude)}
center={new google.maps.LatLng(props.latitude, props.longitude)}
zoom={17}
>
{<Polyline path={props.polylineCords}
geodesic={true}
options={{
strokeColor: "#1e9494",
strokeOpacity: 0.75,
strokeWeight: 2,
icons: [
{
icon: "lineSymbol",
offset: "0",
repeat: "20px"
}
]
}}
/>}
{<Marker
options={{icon: {url: "../../public/images/red-mark.svg", scaledSize: new window.google.maps.Size(30, 62)}}}
position={{ lat: props.latitude, lng: props.longitude }}
onClick={props.onMarkerClick} />
}
</GoogleMap>
);
export { HistoryView };
Now how do I move this marker like a car on location updates?
I use states to update the position of the marker but it doesn't animate. How do I do this?
My issue is when a latlng is updated the marker jumps from one place to another but I want it to move like a car. Have you ever tracked an Uber ride on the web? something like that.
Gif for car animation
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. :)
I am trying to get the map to be centered to the defaultMarker. However, when the map finish loading the view was slightly above the default marker. I have to scroll down to the middle to see the defaultMarker.
Any idea how I can center the view when the map is loaded? I am using React, redux, and react-google-maps.
import React, {Component} from 'react';
import {withGoogleMap, GoogleMap, Marker} from "react-google-maps";
import {connect} from 'react-redux';
class VenuesMap extends Component {
render() {
let markers;
if (this.props.venues !== null) {
markers = this.props.venues.map((venue, i) => {
return (
<Marker
key={i}
position={{ lat: venue.location.lat, lng: venue.location.lng}}
/>
)
})
} else {
markers = <Marker position={{ lat: 40.7589, lng:-73.9851}}/>
}
const MapWithAMarker = withGoogleMap(props =>
<GoogleMap
defaultCenter={{ lat: 40.7589, lng: -73.9851 }}
center={{ lat: 40.7589, lng: -73.9851 }}
zoom={15}
>
{markers}
</GoogleMap>
);
const googleMap = <MapWithAMarker
containerElement={<div style={{
height: `410vh`
}} />}
mapElement={<div style={{ height: `410vh`
}} />}
/>
return (
<div>
{googleMap}
</div>
)
}
}
const stateToProps = (state) => {
return {venues: state.venue.venues}
}
export default connect(stateToProps)(VenuesMap)
maximum window height is 100vh.
just try height: 100vh or less.
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