Google Map info window not loading - React - reactjs

I'm very new to React, but I've managed to build a functioning Google Map component that is successfully centering in a location derived from a search and populating the map with results from Json results. However, I can't get an Info Window to show when clicking one of the map markers and I don't know where I'm going wrong.
Here's the code for the Map Marker and the Info Window:
const ReactMapComponent = ({ text }) => (<div style={{ background: 'url(/olb/images/mapMarker.png)', height: '44px', width: '35px', cursor: 'pointer' }}>{}</div>);
const InfoWindow = ({ text }) => (<div style={{ background: '#fff', height: '100px', width: '135px', cursor: 'pointer', position: 'relative', zIndex: 100 }}>{}</div>);
class VenueMapChild extends React.Component {
constructor(props) {
super(props);
this.state = {
isOpen: false
}
}
handleToggleOpen = () => {
this.setState({
isOpen: true
});
};
handleToggleClose = () => {
this.setState({
isOpen: false,
});
};
render() {
return (
<ReactMapComponent
key={this.props.key}
lat={this.props.lat}
lng={this.props.lng}
text={this.props.hotelName}
onClick={() => this.handleToggleOpen()}
>
{this.state.isOpen &&
<InfoWindow onCloseClick={() => this.handleToggleClose()}>
<span>Something</span>
</InfoWindow>
}
</ReactMapComponent>
);
}
}
Thanks in advance

Related

React Select with avatar class component whats wrong here select not populating

Hi I had working select box with avatar on functional aporx. But I need build in functions to change selectbox properties like hidden: true/false, update option data function to add new option data to display selectbox with certain values on fly.
What I wrong here? Render part works as tested with functional version. The class factoring misses something as select box does not get info ether options and avatar to display and no width calculation happening.
Orginal functional code: https://codesandbox.io/s/react-select-longest-option-width-geunu?file=/src/App.js
Class based works but nodatin selectbox. Here is app.js with select.js fiddle: https://codesandbox.io/s/react-select-longest-option-width-forked-plqq0p?file=/src/Select.js
Source:
import React, { useRef } from "react";
import Select from "react-select";
class RtSelect extends React.Component {
constructor(props) {
super();
this.state = {
info: props.info,
options: props.options,
hidden: props.hidden,
menuIsOpen: false,
menuWidth: "",
IsCalculatingWidth: false
};
this.selectRef = React.createRef();
this.onMenuOpen = this.onMenuOpen.bind(this);
}
componentDidMount() {
if (!this.menuWidth && !this.isCalculatingWidth) {
setTimeout(() => {
this.setState({IsCalculatingWidth: true});
// setIsOpen doesn't trigger onOpenMenu, so calling internal method
this.selectRef.current.select.openMenu();
this.setState({MenuIsOpen: true});
}, 1);
}
}
onMenuOpen() {
if (!this.menuWidth && this.isCalculatingWidth) {
setTimeout(() => {
const width = this.selectRef.current.select.menuListRef.getBoundingClientRect()
.width;
this.setState({menuWidth: width});
this.setState({IsCalculatingWidth: false});
// setting isMenuOpen to undefined and closing menu
this.selectRef.current.select.onMenuClose();
this.setState({MenuIsOpen: true});
}, 1);
}
}
styles = {
menu: (css) => ({
...css,
width: "auto",
...(this.isCalculatingWidth && { height: 0, visibility: "hidden" })
}),
control: (css) => ({ ...css, display: "inline-flex " }),
valueContainer: (css) => ({
...css,
...(this.menuWidth && { width: this.menuWidth })
})
};
setData (props) {
this.setState({
info: props.info,
options: props.options,
hidden: props.hidden
})
}
render() {
return (
<div style={{ display: "flex" }}>
<div style={{ margin: "8px" }}>{this.info}</div>
<div>
<Select
ref={this.selectRef}
onMenuOpen={this.onMenuOpen}
options={this.options}
menuIsOpen={this.menuIsOpen}
styles={this.styles}
isDisabled={this.hidden}
formatOptionLabel={(options) => (
<div className="select-option" style={{ display: "flex" }}>
<div style={{ display: "inline", verticalAlign: "center" }}>
<img src={options.avatar} width="30px" alt="Avatar" />
</div>
<div style={{ display: "inline", marginLeft: "10px" }}>
<span>{options.label}</span>
</div>
</div>
)}
/>
</div>
</div>
);
}
}
export default RtSelect;
Got it working!
I had removed "undefined" from onOpen setState function. I compared those 2 fiddles and finally got it working.
// setting isMenuOpen to undefined and closing menu
this.selectRef.current.select.onMenuClose();
this.setState({MenuIsOpen: undefined});

React-Google-Maps API: How to search current location for a search result?

I'm trying to build a similar map as on Airbnb, where you can view place markers as you drag the map around. I would like to search for "treatment centers" and place markers using the Google Places API on a map.
I have been using the new, re-written #react-google-maps/api. So far, I was able to create both a search box and an autocomplete and get their latitude and longitude, but both offer only specific locations rather than the most similar searches (ex. if you search Taco Bell on Google Maps, it shows up with several options near you). The code below displays a map with the search box:
import { GoogleMap, LoadScript, Marker, StandaloneSearchBox, Autocomplete } from '#react-google-maps/api';
class HeaderMap extends Component {
constructor (props) {
super(props)
this.autocomplete = null
this.onLoad = this.onLoad.bind(this)
this.onPlaceChanged = this.onPlaceChanged.bind(this)
this.state = {
currentLocation: {lat: 0, lng: 0},
markers: [],
zoom: 8
}
}
componentDidMount() {
navigator?.geolocation.getCurrentPosition(({coords: {latitude: lat, longitude: lng}}) => {
const pos = {lat, lng}
this.setState({currentLocation: pos})
})
}
onLoad (autocomplete) {
console.log('autocomplete: ', autocomplete)
this.autocomplete = autocomplete
}
onPlaceChanged() {
if (this.autocomplete !== null) {
let lat = this.autocomplete.getPlace().geometry.location.lat()
let long = this.autocomplete.getPlace().geometry.location.lat()
} else {
console.log('Autocomplete is not loaded yet!')
}
}
render() {
return (
<LoadScript
googleMapsApiKey="API_KEY_HERE"
libraries={["places"]}
>
<GoogleMap
id='search-box-example'
mapContainerStyle={containerStyle}
center={this.state.currentLocation}
zoom={14}
// onDragEnd={search for centers in current location}
>
<Marker key={1} position={this.state.currentLocation} />
<Autocomplete
onLoad={this.onLoad}
onPlaceChanged={this.onPlaceChanged}
>
<input
type="text"
placeholder="Customized your placeholder"
style={inputStyles}
/>
</Autocomplete>
</GoogleMap>
</LoadScript>
);
}
}
How can I automatically search the bounds of the location and get the latitude and longitude of each result based on keywords? Thanks for your help!
In your current code, it seems that you are using Autocomplete which was precoded by the library to have the functions of Places Autocomplete. You can use the StandaloneSearchBox to achieve your use case as it is implementing the Places Searchbox which returns a pick list that includes both places and predicted search terms.
Here is the code sample and code snippet below:
/*global google*/
import React from "react";
import { GoogleMap, StandaloneSearchBox, Marker } from "#react-google-maps/api";
let markerArray = [];
class Map extends React.Component {
state = {
currentLocation: { lat: 0, lng: 0 },
markers: [],
bounds: null
};
onMapLoad = map => {
navigator?.geolocation.getCurrentPosition(
({ coords: { latitude: lat, longitude: lng } }) => {
const pos = { lat, lng };
this.setState({ currentLocation: pos });
}
);
google.maps.event.addListener(map, "bounds_changed", () => {
console.log(map.getBounds());
this.setState({ bounds: map.getBounds() });
});
};
onSBLoad = ref => {
this.searchBox = ref;
};
onPlacesChanged = () => {
markerArray = [];
let results = this.searchBox.getPlaces();
for (let i = 0; i < results.length; i++) {
let place = results[i].geometry.location;
markerArray.push(place);
}
this.setState({ markers: markerArray });
console.log(markerArray);
};
render() {
return (
<div>
<div id="searchbox">
<StandaloneSearchBox
onLoad={this.onSBLoad}
onPlacesChanged={this.onPlacesChanged}
bounds={this.state.bounds}
>
<input
type="text"
placeholder="Customized your placeholder"
style={{
boxSizing: `border-box`,
border: `1px solid transparent`,
width: `240px`,
height: `32px`,
padding: `0 12px`,
borderRadius: `3px`,
boxShadow: `0 2px 6px rgba(0, 0, 0, 0.3)`,
fontSize: `14px`,
outline: `none`,
textOverflow: `ellipses`,
position: "absolute",
left: "50%",
marginLeft: "-120px"
}}
/>
</StandaloneSearchBox>
</div>
<br />
<div>
<GoogleMap
center={this.state.currentLocation}
zoom={10}
onLoad={map => this.onMapLoad(map)}
mapContainerStyle={{ height: "400px", width: "800px" }}
>
{this.state.markers.map((mark, index) => (
<Marker key={index} position={mark} />
))}
</GoogleMap>
</div>
</div>
);
}
}
export default Map;

(google-maps-react) Material-UI popover detail bubble won't follow map marker when map centers to marker (LatLng)

I'm building a map with map markers that show a detail bubble built with the Material-UI Popover component. My code centers the marker when it is clicked, but the detail bubble/popover remains in the spot over where the map marker was before it was centered.
Here is a pic of the detail bubble/Popover when the map marker is centered:
I already tried positioning the detail bubble/popover as such:
.popover {
position: element(#map-marker);
transform: translateY(-100%);
}
But it still behaves the same. I think the popover component
can't calculate the change in the positioning of the map marker because the change is dictated by lat/lng values for the center of the map. I just can't think of any way to circumvent this.
Here is the full code:
Map.js
class ShowsMap extends Component {
constructor(props) {
super(props);
this.state = {
detailBubbleAnchorEl: null // The currently selected marker that the popover anchors to
}
}
handleDetailClose = () => {
this.setState({
detailBubbleAnchorEl: null
})
}
handleMarkerClick = (event, lat, lng) => {
this.setState({
detailBubbleAnchorEl: event.currentTarget
})
// Set center coordinates of map to be those of the map marker (redux action)
this.props.setSearchCenter({ lat, lng })
}
renderMap = () => {
const { detailBubbleAnchorEl } = this.state;
const detailOpen = Boolean(detailBubbleAnchorEl);
const { viewport } = this.props.searchLocation;
const { zoom } = fitBounds(viewport, { width: 400, height: 600})
return (
<GoogleMapReact
yesIWantToUseGoogleMapApiInternals
bootstrapURLKeys={{ key: MYAPIKEY }}
defaultCenter={this.props.center}
defaultZoom={this.props.zoom}
zoom={zoom + 1}
center={this.props.searchLocation.center}
onGoogleApiLoaded={({ map, maps }) => this.handleApiLoaded(map, maps)}
>
{
showLocations.map((location, index) => {
const { lat, lng } = location;
return (
<div lat={lat} lng={lng} key={index}>
<MapMarker onClick={(event) => this.handleMarkerClick(event, lat, lng)} />
<DetailBubble
id="event"
open={detailOpen}
anchorEl={detailBubbleAnchorEl}
onClose={this.handleDetailClose}
/>
</div>
)
})
}
</GoogleMapReact>
)
}
render() {
return (
<div ref={map => this.map = map} style={{ width: '100%', height: '100%',}}>
{this.renderMap()}
</div>
);
}
DetailBubble.js
const DetailBubble = ({ classes, open, anchorEl, onClose, id }) => {
return(
<Popover
id={id}
classes={{ paper: classes.container}}
open={open}
anchorEl={anchorEl}
onClose={onClose}
anchorOrigin={{
vertical: 'top',
horizontal: 'center'
}}
transformOrigin={{
vertical: 'bottom',
horizontal: 'center'
}}
>
</Popover>
)
}
const styles = theme => ({
container: {
position: 'absolute',
left: 0,
top: 0,
right: 0,
bottom: 0,
width: '200px',
height: '150px'
}
});
MapMarker.js
const styles = theme => ({
markerContainer: {
position: 'absolute',
width: 35,
height: 35,
left: -35 / 2,
top: -35 / 2,
},
marker: {
fill: '#3f51b5',
'&:hover': {
fill: 'blue',
cursor: 'pointer'
}
}
})
function MapMarker({ classes, onClick }) {
return (
<div className={classes.markerContainer}>
<Marker onClick={onClick} className={classes.marker} width={30} height={30} />
</div>
)
}
Thanks in advance for your help!

Toggle Button Group in React

New to react and trying to use in a new electron learning project I have. I'm trying to build a really basic drawing app.
I created a ToolbarButton class. That would represent each button and a Toolbar that would manage the button group. Example If you pick a 'primary' tool then it should turn off all other primary tools and leave only your current selection.
In jQuery I'd just do something like
let button = $(this);
let toolbar = $(this).parent();
toolbar.find('button.toolbar-button').removeClass('active');
button.addClass('active');
How would I do the same in react? I can toggle what I want to with setState from within the ToggleButton but separating it out into a prop seems to be an answer, but then I need to have the Toolbar manage the button 'active' states and I'm not sure how to do that. Think the answer is in ReactDOM, super newbie to react so apologize if the answer is overly obvious.
import React from 'react';
import FontAwesome from 'react-fontawesome';
import { ButtonGroup } from 'react-bootstrap';
import { ChromePicker} from 'react-color';
class ToolbarButton extends React.Component
{
state =
{
active: false
}
handleClick = ()=> {
if(this.props.onClick)
{
this.props.onClick();
}
this.setState({ active: !this.state.active});
}
render(){
return <div className={`btn btn-primary${this.state.active ? ' active' : ''}`} onClick={this.handleClick}>{this.props.children}</div>
}
}
class ColorPickerButton extends React.Component
{
constructor(props)
{
super(props);
this.state = {
displayColorPicker: false,
color: { r: 255, g: 255, b: 255, a:1 }
}
}
state = {
flyout: 'bottom',
displayColorPicker: false,
color: { r: 255, g: 255, b: 255, a:1 }
}
/* This button should have an option to display how the colorpicker flys out */
static flyoutStyles =
{
normal: { },
top: {top: '0px' },
bottom: { top: '100%' },
left: { right: '100%' },
right: { left: '100%' }
}
handleClick = (e) => {
this.setState({ displayColorPicker: !this.state.displayColorPicker});
}
handleClose = () => {
this.setState({ displayColorPicker: false });
}
handleChange = (color) => {
this.setState({ color: color.rgb });
}
stopPropagation = (e) => {
e.stopPropagation();
}
render()
{
const swatchStyle = {
backgroundColor: `rgba(${this.state.color.r},
${this.state.color.g},
${this.state.color.b},
${this.state.color.a})`,
height: '16px',
width: '16px',
border: '1px solid white'
};
const popup = {
position: 'absolute',
zIndex: 2,
top: 'calc(100% + 2px)'
};
const cover = {
position: 'fixed',
top: '0px',
right: '0px',
left: '0px',
bottom: '0px',
};
return (
<ToolbarButton onClick={this.handleClick} active={this.state.displayColorPicker}>
<div style={swatchStyle} />
{
this.state.displayColorPicker ?
<div style={popup} onClick={this.stopPropagation}>
<div style={ cover } onClick={ this.handleClose }/>
<ChromePicker color={this.state.color} onChange={this.handleChange} />
</div>
: null
}
</ToolbarButton>
);
}
}
export class CanvasToolbar extends React.Component
{
handleClick = (e) => {
}
render(){
return (<div className="CanvasToolbar">
<ButtonGroup vertical>
<ToolbarButton>
<FontAwesome name='paint-brush' />
</ToolbarButton>
<ToolbarButton>
<FontAwesome name='eraser' />
</ToolbarButton>
<ToolbarButton>
<FontAwesome name='magic' />
</ToolbarButton>
<ColorPickerButton />
</ButtonGroup>
</div>);
}
}

How do I add an image to the DOM after another image has loaded?

I want to make sure images are loaded in the right order: first the primary image, then the secondary image. My plan is to inject the secondaryImage once the primary image is done.
class HoverImage extends Component {
constructor (props) {
super(props)
this.state = { secondaryImage: null }
}
primaryImageLoaded () {
//here I would like inject <img className='img-responsive' src={stripUrl(secondaryImage)} /> before primaryImage
}
render () {
const primaryImage = this.props.primaryImage
const secondaryImage = this.props.secondaryImage
if (secondaryImage) {
return (
<div style={{position: 'relative'}}>
<img
className='img-responsive'
src={stripUrl(primaryImage)}
onLoad={this.primaryImageLoaded.bind(this)}
style={{
':hover': {
opacity: 0
},
position: 'absolute',
top: 0}}
/>
</div>
)
}
}
other solutions that create the same effect are fine too!
Try this:
class HoverImage extends Component {
constructor (props) {
super(props)
this.state = {
secondaryImage: null,
showSecondaryImage: false,
}
}
primaryImageLoaded () {
this.setState({showSecondaryImage: true});
}
render () {
const primaryImage = this.props.primaryImage;
const secondaryImage = this.props.secondaryImage;
secondaryImage ?
return (
<div style={{position: 'relative'}}>
{this.state.showSecondaryImage ?
<img className='img-responsive' src={stripUrl(secondaryImage)} />
: <div/>}
<img
className='img-responsive'
src={stripUrl(primaryImage)}
onLoad={this.primaryImageLoaded.bind(this)}
style={{
':hover': {
opacity: 0
},
position: 'absolute',
top: 0
}}
/>
</div>
)
: return <div/>
}
}
jsfiddle link: http://jsfiddle.net/d7hwzapc/
class HoverImage extends Component {
constructor (props) {
super(props)
this.state = {
firstImageLoaded: false,
};
}
componentDidMount() {
this.setState({ firstImageLoaded: true });
}
loadSecondImage() {
if(this.state.firstImageLoaded) {
return (<img
className='img-responsive'
src={stripUrl(this.props.secondaryImage)}
/>);
}
}
render () {
return (
<div style={{position: 'relative'}}>
<img
className='img-responsive'
src={stripUrl(this.props.primaryImage)}
onLoad={this.setState({ firstImageLoaded: true })}
style={{
':hover': {
opacity: 0
},
position: 'absolute',
top: 0}}
/>
{this.loadSecondImage()}
</div>
)
}
When the initial mount is done, it will set a flag in the state which will trigger a re-render.
Hope that helps!
ps: this answer is in no way perfect but should get what you wanted done.

Resources