How to change defaultCenter in react-google-maps ?
I need to find my geolocation and change default values lat and lng.
import React from "react";
import { withScriptjs, withGoogleMap, GoogleMap, Marker } from "react-google-maps";
const getLocation = () =>{
const pos = {};
const geolocation = navigator.geolocation;
if (geolocation) {
geolocation.getCurrentPosition(findLocal, showEror);
}
function findLocal(position){
pos.lat = position.coords.latitude;
pos.lng = position.coords.longitude;
}
function showEror(){console.log(Error)}
return pos;
};
const myLocation = getLocation(); // object has lat and lng
I need to transfer my data to the component MapWithAMarker next: Сenter={myLocation} and Marker position={myLocation}
class GoogleMapCenter extends React.Component{
render(){
const MapWithAMarker = withScriptjs(withGoogleMap(props =>
<GoogleMap
defaultZoom={10}
defaultCenter={{ lat: -34.397, lng: 150.644 }}>
{props.isMarkerShown && <Marker position={{ lat: -34.397, lng: 150.644 }} />}
</GoogleMap>
));
return(
<MapWithAMarker
isMarkerShown
googleMapURL="https://maps.googleapis.com/maps/api/js?key=AIzaSyC4R6AN7SmujjPUIGKdyao2Kqitzr1kiRg&v=3.exp"
loadingElement={<div style={{ height: `100%` }} />}
containerElement={<div style={{ height: `400px` }} />}
mapElement={<div style={{ height: `100%` }} />}
/>
)
}
}
export default GoogleMapCenter;
If I use this.props, it does not work.
<MapWithAMarker
center={this.props.myLocation}
position={this.props.myLocation}
isMarkerShown
googleMapURL="https://maps.googleapis.com/maps/api/js?key=AIzaSyC4R6AN7SmujjPUIGKdyao2Kqitzr1kiRg&v=3.exp"
loadingElement={<div style={{ height: `100%` }} />}
containerElement={<div style={{ height: `400px` }} />}
mapElement={<div style={{ height: `100%` }} />}
/>
or
<GoogleMap
defaultZoom={10}
defaultCenter={this.props.myLocation}>
{props.isMarkerShown && <Marker position={this.props.myLocation} />}
</GoogleMap>
Default properties like defaultCenter could only be set as initial state, center property could be used instead to re-render (center) the map.
The following example demonstrates how to center the map based on current location
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
currentLatLng: {
lat: 0,
lng: 0
},
isMarkerShown: false
}
}
showCurrentLocation = () => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
position => {
this.setState(prevState => ({
currentLatLng: {
...prevState.currentLatLng,
lat: position.coords.latitude,
lng: position.coords.longitude
},
isMarkerShown: true
}))
}
)
} else {
error => console.log(error)
}
}
componentDidMount() {
this.showCurrentLocation()
}
render() {
return (
<div>
<MapWithAMarker
isMarkerShown={this.state.isMarkerShown}
currentLocation={this.state.currentLatLng} />
</div>
);
}
}
where
const MapWithAMarker = compose(
withProps({
googleMapURL: "https://maps.googleapis.com/maps/api/js",
loadingElement: <div style={{ height: `100%` }} />,
containerElement: <div style={{ height: `400px` }} />,
mapElement: <div style={{ height: `100%` }} />,
}),
withScriptjs,
withGoogleMap
)((props) =>
<GoogleMap
defaultZoom={8}
center={{ lat: props.currentLocation.lat, lng: props.currentLocation.lng }}
>
{props.isMarkerShown && <Marker position={{ lat: props.currentLocation.lat, lng: props.currentLocation.lng }} onClick={props.onMarkerClick} />}
</GoogleMap>
)
Demo (edit)
Related
I'm rendering a GoogleMap component using the "react-google-maps" library in React. I can set an initial defaultLocation that works fine when the map initially loads. In the documentation it says that the component takes a "center" prop that one can pass a lat and a lng to but I can't get it to re-render/re-center to a new location. It always shows the default location. Any idea what I am doing wrong?
Is there maybe a way how I can use state outside of the addAdressComponent class so I can dynamically set the initial defaultCenter instead of using props in the render section?
import { withGoogleMap, GoogleMap, Marker } from 'react-google-maps';
/*global google*/
const MapWithMarker = withGoogleMap((props) => (
<GoogleMap
defaultZoom={12}
defaultCenter={{ lat: 47.376888, lng: 8.541694 }}
options={{
disableDefaultUI: true,
}}
>
<Marker position={{ lat: 47.376888, lng: 8.541694 }} />
</GoogleMap>
));
class addAddressComponent extends Component {
constructor(props) {
super(props);
this.state = {
lat: 0,
lng: 0,
};
this.onSuggestSelect = this.onSuggestSelect.bind(this);
}
onSuggestSelect(suggest) {
console.log(suggest.location);
this.setState(() => {
return {
lat: 10.0,
lng: 20.022,
};
});
}
render() {
return (
<div className="wrapperClass">
<MapWithMarker
containerElement={<div style={{ height: '244px' }} />}
mapElement={<div style={{ height: '100%' }} />}
className="mapCSS"
center={(this.state.lat, this.state.lng)}
style={{
width: '348px',
height: '250px',
}}
/>
</div>
);
}
}
export default addAddressComponent;
You'll need to pass the center property to your GoogleMap component inside your MapWithMarker component. Also the center argument needs to be an object like this:
{ lat: -34.397, lng: 150.644 }
The following example lets you change the center of the map using the button:
import logo from './logo.svg';
import './App.css';
import { withScriptjs, withGoogleMap, GoogleMap, Marker } from 'react-google-maps';
import {useState} from "react";
const MyMapComponent = withScriptjs(withGoogleMap((props) =>
<GoogleMap
defaultZoom={13}
center={props.center}
defaultCenter={{ lat: -34.397, lng: 150.644 }}
>
{props.isMarkerShown && <Marker position={{ lat: -34.397, lng: 150.644 }} />}
</GoogleMap>
))
function App() {
const [position, setPosition] = useState({ lat: -34.397, lng: 150.644 });
return (
<div className="App">
<button onClick={() => setPosition({lat: 30, lng: 10})}>,
Click me
</button>
<MyMapComponent
isMarkerShown
googleMapURL="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry,drawing,places"
loadingElement={<div style={{ height: `100%` }} />}
containerElement={<div style={{ height: `100%` }} />}
center={position}
mapElement={<div style={{ height: `1000px`}} />}
/>
</div>
);
}
export default App;
I'm having a problem in my code. I already can make a marker on the map with lat and lng. But I want to display a simple span with the coordinates under the map. I try to access this.props.markerPosition and it's null in render.
What is the issue here?
https://stackblitz.com/edit/react-snxake
const WrappedMap = compose(
withStateHandlers(() => ({
isMarkerShown: false,
markerPosition: null
}), {
onMapClick: ({ isMarkerShown }) => (e) => ({
markerPosition: e.latLng,
isMarkerShown:true
})
}),
withScriptjs,
withGoogleMap
)
(props =>
<GoogleMap
defaultZoom={8}
defaultCenter={{ lat: -34.397, lng: 150.644 }}
onClick={props.onMapClick}
>
{props.isMarkerShown && <Marker position={props.markerPosition} onClick={props.onMarkerClick} defaultOptions={{ styles: mapStyles}} />}
</GoogleMap>
)
export default class ParkingSpotsSettings extends React.Component {
state = {
evaluationExecuted: false,
evaluation: false
};
constructor() {
super();
this.state = {
coordinates: [],
title: '',
description: '',
capacity: 0
}
}
componentDidMount() { }
render() {
return (
<div className="App">
<Navigation />
<div className="container-fluid">
<div className="row">
<div className="col-md-6" style={{ width: "100vw", height: "40vh" }}>
<WrappedMap googleMapURL={`https://maps.googleapis.com/maps/api/js?key=v=3.exp&libraries=geometry,drawing,places`}
loadingElement={<div style={{ height: "100%" }} />}
containerElement={<div style={{ height: "100%" }} />}
mapElement={<div style={{ height: "100%" }} />}
/>
</div>
<span>Coordinates are: {this.props.markerPosition}</span>
</div>
</div>
</div >
);
}
}
Your prop is called position not markerPosition. So you need to use this.props.position.
I try to pass an array of the markers' coordinates and some other props from the index page (parent of the CardTransactionMapRGMs component) to the map function, so it can use the data to map the Markers. However, I can get the props in the CardTransactionMapRGMs, but I don't know how to get it in the Map function or how to reorganize it.
Also I'm quite confused about this "const WrapperMap = withScriptjs(withGoogleMap(Map));"
Thank you so much! Here's my code:
in index.js
<CardTransactionMapRGMs charges={this.state.charges} coordinates={this.state.coordinates} />
in CardTransactionMapRGMs.js
import React, { Component } from 'react';
import axios from 'axios';
import { GoogleMap, Marker, withScriptjs, withGoogleMap } from "react-google-maps";
import Constants from '../Constants';
import MapMarker from './MapMarker';
function Map() {
return (
<GoogleMap
defaultZoom={10}
defaultCenter={{ lat: 38.96, lng: -77.29 }}
>
//I want to use {props.coordinates.map(e)=> {
// <Marker...>}}here
<Marker position={{ lat: 38.96, lng: -77.29 }} />
</GoogleMap>
)
}
class CardTransactionMapRGMs extends Component {
render() {
const WrapperMap = withScriptjs(withGoogleMap(Map));
return (
<div>
<WrapperMap
googleMapURL={`https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry,drawing,places&key=${Constants.GOOGLE_MAP_API_KEY}`}
loadingElement={<div style={{ height: '100%' }}></div>}
containerElement={<div style={{ height: `400px` }} />}
mapElement={<div style={{ height: `100%` }} />}
/>
</div>
);
}
}
export default CardTransactionMapRGMs;
You can just use your props in your Map functional component.
function Map(props){
return <GoogleMap
defaultZoom={10}
defaultCenter={{ lat: 38.96, lng: -77.29 }}>
{props.coordinates.map(markerProps)=> <Marker {markerProps}>}
<Marker position={{ lat: 38.96, lng: -77.29 }} />
</GoogleMap>
}
CardTransactionMapRGMs.js
class CardTransactionMapRGMs extends Component {
render() {
const WrapperMap = withScriptjs(withGoogleMap(Map));
return (
<div>
<WrapperMap
googleMapURL={`https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry,drawing,places&key=${Constants.GOOGLE_MAP_API_KEY}`}
loadingElement={<div style={{ height: '100%' }}></div>}
containerElement={<div style={{ height: `400px` }} />}
mapElement={<div style={{ height: `100%` }} />}
coordinates={[{ lat: 38.96, lng: -77.29 }]}
/>
</div>
);
}
}
I'm trying to put marker when I click on map. react-google-maps documentation is not good and I feel confused.
class Map extends Component {
render() {
const GoogleMapExample = withGoogleMap(props => (
<GoogleMap
center={{ lat: this.props.latitude, lng: this.props.longitude }}
zoom={13}
>
{this.props.markers.map(marker => {
return <SkateMarker key={marker.title} marker={marker} />;
})}
</GoogleMap>
));
return (
<div>
<GoogleMapExample
containerElement={
<div style={{ height: `500px`, width: "1000px" }} />
}
mapElement={<div style={{ height: `100%` }} />}
/>
</div>
);
}
}
export default Map;
The following example demonstrates how to add a marker on map click using react-google-maps:
class MapWithMarkers extends React.Component {
state = {
places: []
};
addMarker(e) {
const newPlace = { id: this.state.places.length, lat: e.latLng.lat(), lng: e.latLng.lng() };
this.setState({
places: [...this.state.places,newPlace]
})
}
render() {
return (
<GoogleMap
onClick={this.addMarker.bind(this)}
defaultZoom={this.props.zoom}
defaultCenter={this.props.center}
>
{this.state.places.map(place => {
return (
<Marker
key={place.id}
position={{ lat: place.lat, lng: place.lng }}
/>
);
})}
</GoogleMap>
);
}
}
Demo
This is probably going to be a stupidly simple react question but please bear with me.
I am trying to run a react-google-maps with multiple markers with info windows. Here is the code:
const MapWithADirectionsRenderer = compose(
withProps({
googleMapURL: "https://maps.googleapis.com/maps/api/js?key=AIzaSyDf-yIqxErTkbWzKhLox7nAANnrfDIY190&libraries=geometry,drawing,places",
loadingElement: <div style={{ height: `100%` }} />,
containerElement: <div style={{ height: `800px` }} />,
mapElement: <div style={{ height: `100%` }} />,
}),
withStateHandlers(() => ({
isOpen: false,
}), {
onToggleOpen: ({ isOpen }) => () => ({
isOpen: !isOpen,
})
}),
withScriptjs,
withGoogleMap,
})
)(props =>
<GoogleMap
defaultZoom={13}
defaultCenter={new google.maps.LatLng(42.357064, -71.062577)}
>
<Marker
position={{ lat: 42.3381437, lng: -71.0475773 }}
onClick={props.onToggleOpen}
>
{props.isOpen && <InfoWindow onCloseClick={props.onToggleOpen}>
<h3>South Boston</h3>
</InfoWindow>}
</Marker>
<Marker
position={{ lat: 42.3875968, lng: -71.0994968 }}
onClick={props.onToggleOpen}
>
{props.isOpen && <InfoWindow onCloseClick={props.onToggleOpen}>
<h3>Somervil</h3>
</InfoWindow>}
</Marker>
{props.directions && <DirectionsRenderer directions={props.directions} />}
</GoogleMap>
);
When I click one of the markers, the info windows for all the markers toggle open. How do I just toggle open the info window of the marker I click?
I would suggest to introduce a component:
class MarkerWithInfoWindow extends React.Component {
constructor() {
super();
this.state = {
isOpen: false
}
this.onToggleOpen = this.onToggleOpen.bind(this);
}
onToggleOpen() {
this.setState({
isOpen: !this.state.isOpen
});
}
render() {
return (<Marker
position={this.props.position}
onClick={this.onToggleOpen}>
{this.state.isOpen && <InfoWindow onCloseClick={this.onToggleOpen}>
<h3>{this.props.content}</h3>
</InfoWindow>}
</Marker>)
}
}
to control info window per marker via MarkerWithInfoWindow state:
<GoogleMap
defaultZoom={13}
defaultCenter={new google.maps.LatLng(42.357064, -71.062577)}>
<MarkerWithInfoWindow position={{ lat: 42.3381437, lng: -71.0475773 }} content="South Boston" />
<MarkerWithInfoWindow position={{ lat: 42.3875968, lng: -71.0994968 }} content="Somervil" />
</GoogleMap>
Demo