Is this the correct usage of React Components? - reactjs

I am new to React. I want to share my components files with you. The code is syntactically correct and executes just fine. I just want to know, if its logically correct and the correct use of concepts such as states.
Is it correct to save lng and lat coords from the GeoLocation API to the MapContainer State?
Is it the correct use of ComponentDidMount() function.
What other ways can I improve the code.
// Map.js
import React from 'react'
import 'bootstrap/dist/css/bootstrap.css';
import GoogleMapReact from 'google-map-react';
function Map(props) {
const screenHeight = window.screen.height;
return (
<div style={{ height: screenHeight - 250 }}>
<GoogleMapReact
bootstrapURLKeys={{ key: "123mykey" }}
center={props.center}
defaultZoom={props.zoom}
></GoogleMapReact>
</div>
);
}
Map.defaultProps = {
center: {
lat: 59.95,
lng: 30.33
},
zoom: 11
};
export default Map
// MapContainer.js
import React from 'react'
import 'bootstrap/dist/css/bootstrap.css';
import Map from './Map'
class MapContainer extends React.Component {
constructor(props) {
super(props);
this.state = {
center: {
lat: 0, lng: 0
}
}
this.getLocation = this.getLocation.bind(this);
this.showPosition = this.showPosition.bind(this);
}
getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(this.showPosition);
} else {
console.log("Geolocation is not supported by this browser.");
}
}
showPosition(position) {
this.setState({
center: {
lat: position.coords.latitude,
lng: position.coords.longitude
}
});
}
componentDidMount() {
this.getLocation();
}
render() {
return (
<div className="row">
<div className="col-md-9">
<Map center={this.state.center} />
</div>
<div className="col-md-3 d-sm-none d-md-block d-none d-sm-block">
<h1>Menu</h1>
</div>
</div>
);
}
}
export default MapContainer

Looks fine to me. You only need to import 'bootstrap/dist/css/bootstrap.css'; in your main index.js file.

Everything seems good, you are doing right
Is it correct to save lng and lat coords from the GeoLocation API to the MapContainer State?
Is it the correct use of ComponentDidMount() function?
Yeah, Why not ?
What other ways can I improve the code.
there are some minor changes like:
1- you can import Component on top and the class definition would be smaller
2- it is a good practice to use arrow function component definition like this
export default (props) => {
const screenHeight = window.screen.height;
return (
<div style={{ height: screenHeight - 250 }}>
<GoogleMapReact
bootstrapURLKeys={{ key: "AIzaSyCV1fQD2VC6HoNbuuSPkE0q_QZvDf117PY" }}
center={props.center}
defaultZoom={props.zoom}
></GoogleMapReact>
</div>
);
}
generally you are using react in right way, keep going

It looks fine at MapContainer (Example 2) but I propose separate your view based logics and the others. For example, the getLocation function is not based on your view (not depending React component or changing the view) so we can plug out this logic function into an independent function later the showPosition function is going to use that function.

Related

My embeded google map is not displaying in my ReactJS

I am building in ReactJs my intent is to embed a map for directions to a business.
I have zero errors in the console, but yet still no display of the map? I read to change 100% on height and width to 1000px tried that and it did not work.
import React, { Component, useEffect } from 'react'
import { Maps, InfoWindow, Marker, GoogleApiWrapper } from 'google-maps-react';
const mapStyles = {
width: '100%',
height: '100%'
};
export class Googlemap extends Component {
render() {
return (
<Maps
google={this.props.google}
zoom={14}
style={mapStyles}
initialCenter={
{
lat: 42.338131411433736,
lng: -83.3935704444211
}
}
/>
);
}
}
export default GoogleApiWrapper({
apiKey: 'AIzaSyAxGE47DeXkR5rBP_wnJ_FS815zcWNwFRE'
})(Googlemap);

ReactJS useState, onClick show InfoWindow

In my react google maps code I am not able to set onclick open InfoWindow. I am referring to this tutorial: https://youtu.be/WZcxJGmLbSo?t=1545
my code:
import React, { useState } from "react";
import {
GoogleMap,
useLoadScript,
Marker,
InfoWindow,
} from "#react-google-maps/api"; // --> using #react package
const libraries = ["places"];
const mapContainerStyle = {
width: "100%",
height: "100vh",
};
const center = {
lat: 51.103807,
lng: 10.057477,
};
export default function App() {
const [setSState, sstate] = React.useState(null);
const { isLoaded, loadError } = useLoadScript({
googleMapsApiKey: process.env.REACT_APP_GOOGLE_KEY,
libraries,
});
if (loadError) return "error loading maps";
if (!isLoaded) return "loading maps";
return (
<div>
<GoogleMap
mapContainerStyle={mapContainerStyle}
zoom={6}
center={{ lat: 50.115509, lng: 8.690508 }}
>
<Marker
position={{ lat: 51.081753, lng: 13.696073 }}
onClick={() => {
sstate(!setSState);
console.log("marker clicked");
}}
}}
></Marker>
</GoogleMap>
</div>
);
}
I am not able to show the marker only when clicked. What shall I do? I am hard coding the data for now. I am still new to props.
And when click the X on marker and click on the marker again it crashes. I know I have to use onCloseClick which when I tried didnt work.
Have a look at the useState Hook docs.
The hook will give you a state variable to use, and a function that can be used to update that variable.
At the top of the component you want to have:
const [centerState, setCenterState] = useState(null);
and then you can use this in the Marker to update the state:
onClick={() => setCenterState(center)}
That will update the state, but in your code you are currently getting center from an object assigned outside of the component, you might want to think about what you are going to set in that state.

Difference between google-map-react and google-maps-react?

While i'm using Google maps in reactjs, I found two different npms like google-map-react and google-maps-react. As i'm beginner of react i'm bit confused what to use(prefer). Although I found this link but it is bit different which is about- Difference between google-map-react and react-google-maps
The following is the sample code for google-map-react
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
};
render() {
return (
// Important! Always set the container height explicitly
<div style={{ height: '100vh', width: '100%' }}>
<GoogleMapReact
bootstrapURLKeys={{ key: /* YOUR KEY HERE */ }}
defaultCenter={this.props.center}
defaultZoom={this.props.zoom}
>
<AnyReactComponent
lat={59.955413}
lng={30.337844}
text="My Marker"
/>
</GoogleMapReact>
</div>
);
}
}
export default SimpleMap;
The following is the sample code for google-maps-react
import React, { Component } from "react";
import { Map, GoogleApiWrapper, Marker } from "google-maps-react";
const mapStyles = {
width: "100%",
height: "100%"
};
class MapContainer extends Component {
constructor(props) {
super(props);
this.state = {
stores: [
{ lat: 47.49855629475769, lng: -122.14184416996333 },
{ latitude: 47.359423, longitude: -122.021071 },
{ latitude: 47.5524695, longitude: -122.0425407 }
]
};
}
displayMarkers = () => {
return this.state.stores.map((store, index) => {
return (
<Marker
key={index}
id={index}
position={{
lat: store.latitude,
lng: store.longitude
}}
onClick={() => console.log("Clicked me..!")}
/>
);
});
};
render() {
return (
<div>
<Map
google={this.props.google}
zoom={8}
style={mapStyles}
initialCenter={{ lat: 47.444, lng: -122.176 }}
>
{this.displayMarkers()}
</Map>
</div>
);
}
}
export default GoogleApiWrapper({
apiKey: "key"
})(MapContainer);
Please help me Which is optimum to use.
Thanks in advance
As far as I have figured out, google-maps-react mainly focuses on drawing geometric shapes like marker, infowindow, polyline, polygon or circle. They also offer lazy loading for the maps. I have used this library in two of my projects.
On the other hand, google-map-react renders a map where you can put a customized react component in any co-ordinate.
Both libraries can be used to implement API services like autocomplete or direction-services.
You may use any one of them according to your needs.
I wanted to use one of these packages in my project and that's where I created sample projects using both packages so I can test the performance. I wanted to plot thousands of markers and my primary requirement was performance.
I found that google-maps-react handles large markers (>= 10000) of dataset better than google-map-react. Please note for my project, I was not allowed to use clusters and all the markers should be visible all the time on the map. The clustering google-map-react works in a decent way even with larger marker datasets.
It is important to note here that the google-map-react package is updated more frequently than google-maps-react. Avg weekly downloads for google-map-react package are 185,833( 13th July 21) while for google-maps-react average weekly downloads 54,750 ( 13th July 21).
Please note for so many people plotting thousands of markers and relative performance are really important so I decided to write as a separate answer. Apologies for not writing specific performance numbers since I was in hurry.

Pigeon Maps Marker Issue

I am trying to integrate a map in react specifically pigeon-maps since it is an open source.But,I am not able to get the co-ordinates from the map.Can anyone give me some code examples.I have set markers and overlay.I am able to center the map but have no idea how to get the latitude and longitude from the map.
Below is the code for the mapcomponent I am trying to create
import React, { Component } from "react";
import styles from "./mapcomponent.module.css";
import Marker from "pigeon-marker";
import Map from "pigeon-maps";
import Overlay from "pigeon-overlay";
class MapComponent extends Component {
constructor(props) {
super(props);
this.state = { lat: null, long: null };
}
componentWillMount() {
this.setState(
{
lat: Number(this.props.lat),
long: Number(this.props.long)
},
() => {
console.log("HERE", this.state.lat, this.state.long);
}
);
}
render() {
return (
<div className={styles.container} width="500px" height="500px">
<Map center={[this.state.lat, this.state.long]} zoom={12}>
<Marker anchor={[this.state.lat, this.state.long]} payload={1} />
<Overlay
anchor={[this.state.lat, this.state.long]}
offset={[120, 79]}
>
<img src="pigeon.jpg" width={240} height={158} alt="" />
</Overlay>
</Map>
</div>
);
}
}
export default MapComponent;
Can anyone help me to and extend marker and manipulate its value
We have to provide the latitude and longitude to plot the marker on map or you can get latitude and longitude from the map events (like onclick)

Anchor Link under Map Component not clickable

I am writing my first React App (using create-react-app) and I wrote a Map component using google-maps-react. However, the links BELOW the map cannot be clicked.
Actually, on my webpage, this issue is present only on small and medium-sized screens, while it works perfectly on large screens (small, medium and large as defined by materializecss). I tried to reproduce the issue on a minimal working example, without materialize, just using the boilerplate code created by `npx create-react-app my-app' and adding the following:
MapComponent.js
import React from 'react';
import { Map, GoogleApiWrapper } from 'google-maps-react';
const mapStyles = {
width: '80vw',
height: '45vw',
marginLeft: 'auto',
marginRight: 'auto',
display: 'block'
};
const MapComponent = (props) => {
return (
<div className="MapComponent">
<div>
Google
</div>
<Map
google={props.google}
zoom={10}
style={mapStyles}
initialCenter={{
lat: 40,
lng: 12
}}
/>
<div>
Google
</div>
</div>
);
}
export default GoogleApiWrapper({
apiKey: "Key"
})(MapComponent);
and then in App.js:
import React, { Component } from 'react';
import MapComponent from './MapComponent';
class App extends Component {
render() {
return (
<div className="Appr">
<MapComponent />
</div>
);
}
}
export default App;
(the key is not reported in the example, so maps will display the frame with an error message, but the issue is the same with the key). The first link to google.com can be clicked and works, while the second does not. Any solution/workaround?
Finally, I went through the source code of google-maps-react and found the solution. It is very simple but rather undocumented. Apart from style the Map component accepts a containerStyle prop, allowing to change the tyle of the container wrapping Map. By default, the position is set to position: absolute giving the aforementioned behavior. The following code solves the issue for me:
import React from 'react';
import { Map, GoogleApiWrapper } from 'google-maps-react';
const mapStyles = {
width: '80vw',
height: '45vw',
marginLeft: 'auto',
marginRight: 'auto',
display: 'block'
};
const containerStyle = { {/* Added style */}
position: 'static'
}
const MapComponent = (props) => {
return (
<div className="MapComponent">
<div>
Google
</div>
<Map
google={props.google}
zoom={10}
style={mapStyles}
containerStyle={containerStyle} {/* Added prop */}
initialCenter={{
lat: 40,
lng: 12
}}
/>
<div>
Google
</div>
</div>
);
}
export default GoogleApiWrapper({
apiKey: "Key"
})(MapComponent);

Resources