I want to display multiple markers with Google Maps React just like this , but my file structure is very different than the example. How can I get it to work with my application?
/* global Google*/
import React, { Component } from "react";
import { Map, GoogleApiWrapper, InfoWindow, Marker } from "google-maps-react";
const mapStyles = {
width: "45%",
height: "54%"
};
export class MapContainer extends Component {
state = {
showingInfoWindow: false, //Hides or the shows the infoWindow
activeMarker: {}, //Shows the active marker upon click
selectedPlace: {} //Shows the infoWindow to the selected place upon a marker
};
onMarkerClick = (props, marker, e) =>
this.setState({
selectedPlace: props,
activeMarker: marker,
showingInfoWindow: true
});
render() {
const google = window.google;
const data = this.props.data;
const center = this.props.center;
return (
<Map
google={this.props.google}
zoom={13}
style={{}}
scrollwheel={true}
initialCenter={{
lat: 32.71573699,
lng: -117.16108799
}}
>
<Marker
onClick={this.onMarkerClick}
name={""}
position={{ lat: 32.71573699, lng: -117.16108799 }}
/>
<InfoWindow
marker={this.state.activeMarker}
visible={this.state.showingInfoWindow}
onClose={this.onClose}
/>
<Marker
onClick={this.onMarkerClick}
name={"John jones Convention Centre"}
position={{ lat: 32.71673699, lng: -117.16308799 }}
/>
<InfoWindow
marker={this.state.activeMarker}
visible={this.state.showingInfoWindow}
onClose={this.onClose}
/>
<Marker
onClick={this.onMarkerClick}
name={"John jones Convention Centre"}
position={
({ lat: 32.714587, lng: -117.16919 },
{ lat: 32.714715, lng: -117.157309 })
}
/>
<Marker
onClick={this.onMarkerClick}
name={"John jones Convention Centre"}
position={{ lat: 32.716848, lng: -117.159111 }}
/>
</Map>
);
}
}
export default GoogleApiWrapper({
apiKey: *****
})(MapContainer);
Any recommendations how to organize my code to copy the sandbox example? I'm very lost with that part. I know how to do it in normal vanilla JavaScript, but not in React.
You can organize your marker data into an array of objects like so:
data: [{onclick: myfunction, name: 'foo', position: coordinates, id: 'something'}]
Then in your render, you can use curly braces to write plain javascript in JSX like so:
render() {
return (
<Map
google={this.props.google}
zoom={13}
style={{}}
scrollwheel={true}
initialCenter={{
lat: 32.71573699,
lng: -117.16108799
}}
>
{ //curly brace here lets you write javscript in JSX
data.map(item =>
<Marker
key={item.id}
title={item.name}
name={item.name}
position={{ lat: item.lat, lng: item.lng }}
/>
)
} //closing brace
<InfoWindow
marker={this.state.activeMarker}
visible={this.state.showingInfoWindow}
onClose={this.onClose}
/>
</Map>
)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.