How to embed an exact place on google maps in Reactjs - javascript

I am redoing my website with Reactjs. I'm trying to embed an exact google place with reviews on the map so it would look like this (My website written with wordpress)
So far I could only display a pin with exact coordinates, and it would look like this
Is there a way to embed an exact place on the maps as the reviews are very important to be visible for my customers?
If I would copy the link with the embedded place like this
<iframe src="https://www.google.com/maps/embed?pb=!1m14!1m8!1m3!1d12063.71295670172!2d-72.388377!3d40.895389!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x0%3A0x46289ec3b50eabb9!2sMove%20Plus!5e0!3m2!1sen!2sus!4v1613186587593!5m2!1sen!2sus" width="600" height="450" frameborder="0" style="border:0;" allowfullscreen="" aria-hidden="false" tabindex="0"></iframe> into my function, the website would crash.
Here's my google maps component :
import React from "react";
import {
withScriptjs,
withGoogleMap,
GoogleMap,
Marker,
} from "react-google-maps";
const MapWrapper = withScriptjs(
withGoogleMap((props) => (
<GoogleMap
defaultZoom={13}
defaultCenter={{ lat: 40.895436, lng: -72.388484 }}
>
<Marker position={{ lat: 40.895436, lng: -72.388484 }} />
</GoogleMap>
))
);
function MyMap() {
return (
<>
<MapWrapper
googleMapURL="https://maps.googleapis.com/maps/api/myAPIHere"
loadingElement={<div style={{ height: `100%` }} />}
containerElement={<div style={{ height: `100%` }} />}
mapElement={<div style={{ height: `100%` }} />}
/>
</>
);
}
export default MyMap;

The map from the screenshot you want to achieve is using Maps Embed API while the "react-google-maps" library in your code is using Maps JavaScript API. These APIs are different and if you want to achieve the one from your screenshot in Reactjs, you can put the directly inside the div that you want to display. You can generate the iframe of your place you can check this link. Just search for your place and it will generate the iframe. Please note that there's a key parameter in the iframe link. This means that you need to put an API key in your request.
Here is a sample code and code snippet below:
import React from "react";
import ReactDOM from "react-dom";
function App() {
return (
<div>
<h1>MAPS!</h1>
<p>Please see map below</p>
<iframe
width="600"
height="450"
style={{ border: 0 }}
loading="lazy"
allowfullscreen
src="https://www.google.com/maps/embed/v1/place?q=place_id:ChIJ92pXbcOV6IkRuasOtcOeKEY&key=YOUR_API_KEY"
/>
</div>
);
}
ReactDOM.render(<App />, document.getElementById("root"));

Here is a code below:
function initMap() {
var mapOptions, map, marker,infoWindow = '',
element = document.getElementById( 'map-canvas' );
mapOptions = {
zoom: 8,
center: new google.maps.LatLng( 0,0 ),
disableDefaultUI: false, // Disables the controls like zoom control on the map if set to true
scrollWheel: true, // If set to false disables the scrolling on the map.
draggable: true, // If set to false , you cannot move the map around.
};
map = new google.maps.Map( element, mapOptions ); // Till this like of code it loads up the map.
marker = new google.maps.Marker({
position: mapOptions.center,
map: map,
// icon: 'http://pngimages.net/sites/default/files/google-maps-png-image-70164.png',
draggable: true
});
}
window.initMap = initMap;
then call the map-search id in your render function
<div id="map-canvas" style={{height:500px, width:800px}}></div>

Related

Why is no 3rd marker being created on map?

I have the below JS code
A map renders just fine and when clicking the 1st click on the map, it creates and pins a marker on the place it was clicked. The 2nd time I click, it creates a 2nd marker and pins to the position that was clicked. Great!
However, when clicking the 3rd time, it doesn't create another marker! It instead moves the 2nd marker to the position of the 3rd click! Why is it doing that? It's supposed to create a 3rd marker, but for some reason, it moves the 2nd marker to a new position which should not be the case.
The marker is inside the tags too <Marker key={i} position={latLng} so it should work properly...
It seems that {props.isMarkerShown && <Marker position={props.markerPosition} />} is not creating a new instance for the marker after the 2nd marker is created for some reason...
import React from 'react';
import { compose, withStateHandlers } from "recompose";
import { InfoWindow, withGoogleMap, withScriptjs, GoogleMap, Marker } from 'react-google-maps';
const Map = 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} />}
</GoogleMap>
)
export default class MapContainer extends React.Component {
constructor(props) {
super(props)
}
render() {
return (
<div style={{ height: '100%' }}>
<Map
googleMapURL="https://maps.googleapis.com/maps/api/js?key=VALIDAPIKEY"
loadingElement={<div style={{ height: `100%` }} />}
containerElement={<div style={{ height: `400px` }} />}
mapElement={<div style={{ height: `100%` }} />}
/>
{clicks.map((latLng, i) => (
<Marker key={i} position={latLng} />
))}
</div>
)
}
}
https://developers.google.com/maps/documentation/javascript/react-map

google-map-react not loading

My Google Map gives following error:
"Oops! Something went wrong. This page didn't load Google Maps correctly. See the JavaScript console for technical details."
I use Gatsby and google-map-react package. My code:
const AnyReactComponent = ({ text }) => <div>{text}</div>;
static defaultProps = {
center: {
lat: 59.95,
lng: 30.33
},
zoom: 11
};
<div style={{ height: '50vh', width: '100%' }}>
<GoogleMapReact
bootstrapURLKeys={{ key: "https://maps.google.com/maps?q=manhatan&t=&z=13&ie=UTF8&iwloc=&output=embed" }}
defaultCenter={this.props.center}
defaultZoom={this.props.zoom}
>
<AnyReactComponent
lat={59.955413}
lng={30.337844}
text="My Marker"
/>
</GoogleMapReact>
</div>
In bootstrapURLKeys you have to add google map api key not url.
you can get key from google console https://developers.google.com/maps/documentation/javascript/get-api-key
<GoogleMapReact
bootstrapURLKeys={{ key: /* YOUR KEY HERE */ }}
......
/>

How to display google map in reactjs inside of page height and width?

I am trying to put a google map on a after some description on page to start in a react project, and am having trouble. I have created google map in another component and calling that googlemap component into main component.
Map is loading correctly, but facing issue with border map is getting out of the section. I have attached image too. I think the problem is with page component height
const Con = () => {
return (
<div className="Contact">
<Container>
<Row>
<Col xs lg="8">
<h1><strong>Contact Us</strong></h1>
<br></br>
<div>
<h5><strong>For any enquiry, please contact Andrew Lal Ji at lalnco#yahoo.co.uk</strong></h5>
<p><strong>Coming by Car: </strong></p>
<p>Please use post code G3 7LH for Sat Nav.</p>
<p><strong>Coming by Bus:</strong></p>
<br></br>
</div>
<div >
< MapWrapper />
</div>
</Col>
</Row>
</Container>
</div>
);
};
Now i used con.js in App.js module
Here is my component google_map.js:
const mapStyles = {
width: '100%',
height: '400px'
}
export class MapContainer extends Component {
render() {
return (
<Map google={this.props.google}
zoom={15}
style={mapStyles}
initialCenter={{ lat: 55.866701, lng: -4.279272}}
>
<Marker position={{ lat: 55.866701, lng: -4.279272}} />
</Map>
);
}
}
export default GoogleApiWrapper({
apiKey: ("mykey")
})(MapContainer)
The issue was coming due to the default CSS set by the Map library. Mostly because of position:absolute; property
I have used my own custom class and updated the CSS.
Note: I have used Styled-Jsx to quickly use my CSS. You can use the same CSS in a seperate CSS file and import it here. Or do npm install --save styled-jsx
Here are the code changes in your LetChangeMap.js file (MapContainer) component:
import React, { Component } from 'react'
import {Map, Marker, GoogleApiWrapper} from 'google-maps-react';
const mapStyles = {
width: '100%',
height: '400px',
}
export class MapContainer extends Component {
render() {
return (
<Map google={this.props.google}
zoom={15}
className="mapContainerWrapper"
style={mapStyles}
initialCenter={{ lat: 55.866701, lng: -4.279272}}
>
<Marker className="mapContainerMarker" position={{ lat: 55.866701, lng: -4.279272}} />
<style jsx>{`
.mapContainerWrapper{
position:relative !important;
}
.mapContainerWrapper div:first-child{
position:relative !important;
}
`}</style>
</Map>
);
}
}
export default GoogleApiWrapper({
apiKey: ("key")
})(MapContainer)
StackBlitz Link: https://stackblitz.com/edit/map-library-issue
StackBlitz Output: https://stackblitz.com/edit/map-library-issue

Google Maps API - How to center marker and map

I have played around with the geolocation of javascript. So I created a react component, which shows your current location. I want to visualize this with Google Maps. It works fine so far, but however, if the current position moves outside the start map, the map does not pan. My goal is that the marker is always centered, and the map scrolls.
This is what I have so far. The current position is being passed to the component via the props props.latitude and props.longitude.
UPDATE
Now I know why this is not working.
window.google.maps.Map(document.getElementsByClassName("google-map"))
is not working. It does not find the map this way. So it cannot update its properties.
Anybody an idea how to access the current map?
Here is the code:
import React, {useState,useRef,useCallback} from 'react';
import { compose, withProps } from "recompose"
import { withScriptjs, withGoogleMap, GoogleMap, Marker } from "react-google-maps"
function Map(props) {
const [center, setCenter] = useState({ lat: props.latitude, lng: props.longitude });
const refMap = useRef(null);
const handlePositionChanged = () => {
let position = new window.google.maps.LatLng(parseInt(props.latitude), parseInt(props.longitude));
window.google.maps.Marker(document.getElementsByClassName("google-map-marker")).setPosition(position);
window.google.maps.Map(document.getElementsByClassName("google-map")).setCenter(position);
};
return (
<GoogleMap
className="google-map"
ref={refMap}
defaultZoom={19}
mapTypeId='satellite'
defaultCenter={{ lat: props.latitude, lng: props.longitude }}
onBoundsChanged={useCallback(handlePositionChanged)}
>
<Marker className="google-map-marker" position={{ lat: props.latitude, lng: props.longitude }} position_changed={useCallback(handlePositionChanged)} />
</GoogleMap>
);
}
export default compose(
withProps({
googleMapURL: "https://maps.googleapis.com/maps/api/js?key=AIz&v=3.exp&libraries=geometry,drawing,places",
loadingElement: <div style={{ height: `100%` }} />,
containerElement: <div style={{ height: `500px` }} />,
mapElement: <div style={{ height: `100%` }} />,
}),
withScriptjs,
withGoogleMap
)((props) => <Map latitude={props.latitude} longitude={props.longitude} />);
Instead of setting the center of the map and the marker using window.google.maps., you can use state values to change the <GoogleMap/> center parameter and the <Marker/> position parameter. So every time there's a change in the coordinates from geolocation, you need to change the state value of the Map's center and Marker's position and it the changes will then be reflected to the map. Here's a sample code snippet:
import React, { Component } from 'react';
import { withGoogleMap, GoogleMap, Marker } from 'react-google-maps';
class Map extends Component {
constructor(props) {
super(props);
this.state = {
userPosition: { lat: 40.756795, lng: -73.954298 }
};
}
onMapLoad = () => {
navigator.geolocation.getCurrentPosition(position => {
const { latitude, longitude } = position.coords;
this.setState({
userPosition: { lat: latitude, lng: longitude }
});
});
};
render() {
const GoogleMapExample = withGoogleMap(props => (
<GoogleMap
center={this.state.userPosition}
defaultZoom={13}
onLoad={this.onMapLoad()}
>
<Marker position={this.state.userPosition} />
</GoogleMap>
));
return (
<div>
<GoogleMapExample
containerElement={<div style={{ height: `500px`, width: '500px' }} />}
mapElement={<div style={{ height: `100%` }} />}
/>
</div>
);
}
}
export default Map;

How to add the Google Maps API key for a React app created with create-react-app using react-google-maps?

I'm trying to use the example component given in Step 5 of https://tomchentw.github.io/react-google-maps/#introduction,
import React from "react"
import { compose, withProps } from "recompose"
import { withScriptjs, withGoogleMap, GoogleMap, Marker } from "react-google-maps"
const MyMapComponent = compose(
withProps({
googleMapURL: "https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry,drawing,places",
loadingElement: <div style={{ height: `100%` }} />,
containerElement: <div style={{ height: `400px` }} />,
mapElement: <div style={{ height: `100%` }} />,
}),
withScriptjs,
withGoogleMap
)((props) =>
<GoogleMap
defaultZoom={8}
defaultCenter={{ lat: -34.397, lng: 150.644 }}
>
{props.isMarkerShown && <Marker position={{ lat: -34.397, lng: 150.644 }} onClick={props.onMarkerClick} />}
</GoogleMap>
))
class MyFancyComponent extends React.PureComponent {
state = {
isMarkerShown: false,
}
componentDidMount() {
this.delayedShowMarker()
}
delayedShowMarker = () => {
setTimeout(() => {
this.setState({ isMarkerShown: true })
}, 3000)
}
handleMarkerClick = () => {
this.setState({ isMarkerShown: false })
this.delayedShowMarker()
}
render() {
return (
<MyMapComponent
isMarkerShown={this.state.isMarkerShown}
onMarkerClick={this.handleMarkerClick}
/>
)
}
}
in a React app created with create-react-app. I've added the above code to components/Map.js, added an export before the class MyFancyComponent, and modified App.js to the following (see https://github.com/khpeek/beomaps/blob/master/src/App.js):
import React from 'react';
import './App.css';
import { MyFancyComponent } from "./components/Map"
function App() {
return (
<div className="App">
<MyFancyComponent/>
</div>
);
}
export default App;
However, if I run npm start and navigate to localhost:3000, I see this error:
So I see an error,
You have exceeded your request quota for this API.
and a warning,
Google Maps JavaScript API warning: NoApiKeys https://developers.google.com/maps/documentation/javascript/error-messages#no-api-keys
According to that warning,
The script element that loads the API has no API key. Please make sure you include a valid API key as a key parameter. You can generate a new API key on the Google Cloud Platform Console.
As I understand from https://github.com/tomchentw/react-google-maps/issues/275, one would fix this by adding
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY" type="text/javascript"></script>
to the index.html. In this example created with create-react-app, however, there is no index.html, only an index.js, so it is unclear to me how to apply this advice.
Any ideas how to add the API key to this example?
You need to set up your Google maps API via key=YOUR_API in
googleMapURL:"https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry,drawing,places",
Just like in Docs
googleMapURL:"https://maps.googleapis.com/maps/api/js?key=AIzaSyC4R6AN7SmujjPUIGKdyao2Kqitzr1kiRg&v=3.exp&libraries=geometry,drawing,places",

Categories