Skip to content

Instantly share code, notes, and snippets.

@kisildev
Created October 18, 2019 10:28
Show Gist options
  • Save kisildev/b2e708bd0852f6002342fe99ed4d6845 to your computer and use it in GitHub Desktop.
Save kisildev/b2e708bd0852f6002342fe99ed4d6845 to your computer and use it in GitHub Desktop.
React google map examples
//Link to repository - https://github.com/google-map-react/google-map-react
import React, { Component } from 'react';
import GoogleMapReact from 'google-map-react';
import Marker from './marker';
import mapStyle from './map-style';
export default class MapContainer extends Component {
renderMarkers() {
const { markersCoords } = this.props;
if (!markersCoords.length) {
return [];
}
return markersCoords.map((markerCoord, index) => (
<Marker
key={index}
lat={markerCoord[0]}
lng={markerCoord[1]}
count={index}
/>
));
}
render() {
const mapOptions = {
styles: mapStyle,
};
return (
<GoogleMapReact
bootstrapURLKeys={{ key: 'api_key' }}
defaultCenter={{ lat: 48.447731, lng: 30.542721 }}
center={{ lat: 48.447731, lng: 30.542721 }}
defaultZoom={6}
options={mapOptions}
>
{this.renderMarkers()}
</GoogleMapReact>
);
}
}
//Marker
import React from 'react';
const Marker = (props) => (
<svg fill="#5db949" viewBox="0 0 34 43" width="34" height="43" className="marker landmark_30eFN fill_primary marker" datad="landmark" data-active="true">
<path clipRule="evenodd" d="M17 0C7.611 0 0 7.611 0 17c0 3.735 1.204 7.188 3.246 9.993h-.004l.074.095c.132.18.267.356.406.53l10.898 14.17a3 3 0 0 0 4.758-.002l10.613-13.82A16.932 16.932 0 0 0 34 17c0-9.389-7.611-17-17-17z"></path>
<text fontFamily="Open Sans, Arial" textAnchor="middle" fontSize="12" alignmentBaseline="central" fontWeight="700" fill="#FFF">
<tspan x="17" y="22">{props.count}</tspan>
</text>
</svg>
);
export default Marker;
//Owner code - https://github.com/titivermeesch/neighborapp-front/blob/master/src/components/Maps.js
import React, { Component } from 'react'
import { Map, GoogleApiWrapper, Marker } from 'google-maps-react'
import { connect } from 'react-redux'
import { saveMapCoords } from '../redux/actions/index'
import { Redirect } from 'react-router-dom'
import { Button } from 'semantic-ui-react'
import InfoWindowEx from './infoWindowEx'
import '../styles/navbar.scss'
const uuidv1 = require('uuid/v1')
export class Maps extends Component {
state = {
data: [],
loc_x: 0,
loc_y: 0,
locRendered: false,
showingInfoWindow: false,
activeMarker: {},
selectedPlace: {},
redirect: false,
redirectId: 0
}
getUserLocation = () => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(this.showPosition)
}
}
showPosition = position => {
this.setState({
loc_x: position.coords.latitude,
loc_y: position.coords.longitude,
locRendered: true
})
}
fetchRequestLocations = () => {
fetch(`https://neighborapp-backend.herokuapp.com/requests/`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'X-User-Email': localStorage.getItem('email'),
'X-User-Token': localStorage.getItem('token')
}
})
.then(res => res.json())
.then(data => {
this.setState({ data: data.data })
setTimeout(() => {
this.fetchRequestLocations()
}, 20000)
})
}
saveCoords = (mapProps, map, clickEven) => {
if (window.location.pathname === '/c/request') {
this.props.saveMapCoords(clickEven.latLng.lat(), clickEven.latLng.lng())
document.querySelector('.custom-modal').style.visibility = 'visible'
document.querySelector('.fader').style.visibility = 'visible'
}
}
openContribution = id => {
document.querySelector('.fader').style.visibility = 'visible'
this.setState({
redirect: true,
redirectId: id,
showingInfoWindow: false
})
}
renderRedirect = () => {
if (this.state.redirect) {
return <Redirect to={`/c/contribution/${this.state.redirectId}`} />
}
}
centerMoved = (mapProps, map) => {
this.setState({
loc_x: map.center.lat(),
loc_y: map.center.lng()
})
}
componentWillMount() {
this.getUserLocation()
}
componentDidMount() {
this.fetchRequestLocations()
}
render() {
return (
<div>
{this.renderRedirect()}
{this.state.locRendered ? (
<Map
google={this.props.google}
zoom={14}
styles={this.props.mapStyles}
disableDefaultUI={true}
onClick={this.saveCoords}
onDragend={this.centerMoved}
initialCenter={{
lat: this.state.loc_x,
lng: this.state.loc_y
}}
>
{this.state.data.map(m => {
if (m.status === 'open') {
if (m.request_type === 'normal') {
return (
<Marker
key={uuidv1()}
position={{ lat: m.x, lng: m.y }}
title={m.title}
data={m}
onClick={this.onMarkerClick}
icon={{
url: '../../data/welfareroom.png',
anchor: new this.props.google.maps.Point(48, 48),
scaledSize: new this.props.google.maps.Size(48, 48)
}}
/>
)
} else {
return (
<Marker
key={uuidv1()}
position={{ lat: m.x, lng: m.y }}
title={m.title}
data={m}
onClick={this.onMarkerClick}
icon={{
url: '../../data/tortillas1.png',
anchor: new this.props.google.maps.Point(48, 48),
scaledSize: new this.props.google.maps.Size(48, 48)
}}
/>
)
}
}
})}
<InfoWindowEx marker={this.state.activeMarker} visible={this.state.showingInfoWindow}>
<div>
<h1>{this.state.selectedPlace.title}</h1>
<div>{this.state.selectedPlace.description}</div>
<br />
<Button onClick={() => this.openContribution(this.state.selectedPlace.id)}>
Read more
</Button>
</div>
</InfoWindowEx>
</Map>
) : null}
</div>
)
}
onMarkerClick = (props, marker) => {
this.setState({
selectedPlace: props.data,
activeMarker: marker,
showingInfoWindow: true,
redirect: false
})
}
}
Maps.defaultProps = {
mapStyles: [
{
elementType: 'geometry',
stylers: [
{
color: '#242f3e'
}
]
},
{
elementType: 'labels.text.fill',
stylers: [
{
color: '#746855'
}
]
},
{
elementType: 'labels.text.stroke',
stylers: [
{
color: '#242f3e'
}
]
},
{
featureType: 'administrative.land_parcel',
elementType: 'labels',
stylers: [
{
visibility: 'off'
}
]
},
{
featureType: 'administrative.locality',
elementType: 'labels.text.fill',
stylers: [
{
color: '#d59563'
}
]
},
{
featureType: 'poi',
elementType: 'labels.text',
stylers: [
{
visibility: 'off'
}
]
},
{
featureType: 'poi',
elementType: 'labels.text.fill',
stylers: [
{
color: '#d59563'
}
]
},
{
featureType: 'poi.business',
stylers: [
{
visibility: 'off'
}
]
},
{
featureType: 'poi.park',
elementType: 'geometry',
stylers: [
{
color: '#263c3f'
}
]
},
{
featureType: 'poi.park',
elementType: 'labels.text',
stylers: [
{
visibility: 'off'
}
]
},
{
featureType: 'poi.park',
elementType: 'labels.text.fill',
stylers: [
{
color: '#6b9a76'
}
]
},
{
featureType: 'road',
elementType: 'geometry',
stylers: [
{
color: '#38414e'
}
]
},
{
featureType: 'road',
elementType: 'geometry.stroke',
stylers: [
{
color: '#212a37'
}
]
},
{
featureType: 'road',
elementType: 'labels.text.fill',
stylers: [
{
color: '#9ca5b3'
}
]
},
{
featureType: 'road.highway',
elementType: 'geometry',
stylers: [
{
color: '#746855'
}
]
},
{
featureType: 'road.highway',
elementType: 'geometry.stroke',
stylers: [
{
color: '#1f2835'
}
]
},
{
featureType: 'road.highway',
elementType: 'labels.text.fill',
stylers: [
{
color: '#f3d19c'
}
]
},
{
featureType: 'road.local',
elementType: 'labels',
stylers: [
{
visibility: 'off'
}
]
},
{
featureType: 'transit',
elementType: 'geometry',
stylers: [
{
color: '#2f3948'
}
]
},
{
featureType: 'transit.station',
elementType: 'labels.text.fill',
stylers: [
{
color: '#d59563'
}
]
},
{
featureType: 'water',
elementType: 'geometry',
stylers: [
{
color: '#17263c'
}
]
},
{
featureType: 'water',
elementType: 'labels.text.fill',
stylers: [
{
color: '#515c6d'
}
]
},
{
featureType: 'water',
elementType: 'labels.text.stroke',
stylers: [
{
color: '#17263c'
}
]
}
]
}
function mapStateToProps(state) {
return {
x: state.x,
y: state.y
}
}
export default connect(
mapStateToProps,
{ saveMapCoords }
)(
GoogleApiWrapper({
apiKey: 'AIzaSyCw1Cu5QmZqsFLWq-D7m12E3Qqjjj13xWY'
})(Maps)
)
import React, { Component } from 'react';
import { Map, GoogleApiWrapper, Marker } from 'google-maps-react';
import MarkerIcon from './marker';
import mapStyle from './map-style';
const mapStyles = {
width: '100%',
height: '100%'
};
export class MapContainer extends Component {
renderMarkers() {
const { markersCoords } = this.props;
if (!markersCoords.length) {
return false;
}
markersCoords.map((markerCoord, index) => {
console.log(markerCoord);
return (
<Marker
key={index}
position={{ lat: markerCoord[0], lng: markerCoord[1] }}
icon={{
url: 'https://img.icons8.com/carbon-copy/100/000000/place-marker.png',
anchor: new this.props.google.maps.Point(48, 48),
scaledSize: new this.props.google.maps.Size(48, 48)
}}
/>
)
});
}
render() {
return (
<Map
styles={mapStyle}
google={this.props.google}
zoom={6}
style={mapStyles}
initialCenter={{
lat: 50.447731,
lng: 30.542721
}}
>
<Marker
key={index}
position={{ lat: '49.5937', lng: '34.5407' }}
icon={{
url: MarkerIcon,
anchor: new this.props.google.maps.Point(48, 48),
scaledSize: new this.props.google.maps.Size(48, 48)
}}
/>
</Map>
);
}
}
// Marker
import React from 'react';
const MarkerIcon = (props) => {
return (
<svg viewBox="0 0 34 43" className="landmark_30eFN fill_primary" datad="landmark" data-active="true">
<path dataFill="true" fillFule="evenodd" clipRule="evenodd" d="M17 0C7.611 0 0 7.611 0 17c0 3.735
1.204 7.188 3.246 9.993h-.004l.074.095c.132.18.267.356.406.53l10.898 14.17a3 3 0 0 0
4.758-.002l10.613-13.82A16.932 16.932 0 0 0 34 17c0-9.389-7.611-17-17-17z">
</path>
<text fontFamily="Open Sans, Arial" textAnchor="middle" fontSize="12" alignmentBaseline="central" fontWeight="700" fill="#FFF">
<tspan x="17" y="22">{this.props.count}</tspan>
</text>
</svg>
);
}
export default MarkerIcon;
// Styles
const mapStyle = [
{
"featureType": "all",
"elementType": "labels.text.fill",
"stylers": [
{
"saturation": 36
},
{
"color": "#333333"
},
{
"lightness": 40
}
]
},
{
"featureType": "all",
"elementType": "labels.text.stroke",
"stylers": [
{
"visibility": "on"
},
{
"color": "#ffffff"
},
{
"lightness": 16
}
]
},
{
"featureType": "all",
"elementType": "labels.icon",
"stylers": [
{
"visibility": "off"
}
]
},
{
"featureType": "administrative",
"elementType": "geometry.fill",
"stylers": [
{
"color": "#fefefe"
},
{
"lightness": 20
}
]
},
{
"featureType": "administrative",
"elementType": "geometry.stroke",
"stylers": [
{
"color": "#fefefe"
},
{
"lightness": 17
},
{
"weight": 1.2
}
]
},
{
"featureType": "administrative.country",
"elementType": "geometry.stroke",
"stylers": [
{
"visibility": "on"
},
{
"color": "#b4b4b4"
}
]
},
{
"featureType": "administrative.province",
"elementType": "labels",
"stylers": [
{
"visibility": "on"
}
]
},
{
"featureType": "administrative.locality",
"elementType": "labels",
"stylers": [
{
"visibility": "on"
}
]
},
{
"featureType": "landscape",
"elementType": "geometry",
"stylers": [
{
"color": "#f5f5f5"
},
{
"lightness": 20
}
]
},
{
"featureType": "poi",
"elementType": "geometry",
"stylers": [
{
"color": "#f5f5f5"
},
{
"lightness": 21
}
]
},
{
"featureType": "poi.park",
"elementType": "geometry",
"stylers": [
{
"color": "#dedede"
},
{
"lightness": 21
}
]
},
{
"featureType": "road.highway",
"elementType": "geometry.fill",
"stylers": [
{
"color": "#ffffff"
},
{
"lightness": 17
}
]
},
{
"featureType": "road.highway",
"elementType": "geometry.stroke",
"stylers": [
{
"color": "#ffffff"
},
{
"lightness": 29
},
{
"weight": 0.2
}
]
},
{
"featureType": "road.arterial",
"elementType": "geometry",
"stylers": [
{
"color": "#ffffff"
},
{
"lightness": 18
}
]
},
{
"featureType": "road.local",
"elementType": "geometry",
"stylers": [
{
"color": "#ffffff"
},
{
"lightness": 16
}
]
},
{
"featureType": "transit",
"elementType": "geometry",
"stylers": [
{
"color": "#f2f2f2"
},
{
"lightness": 19
}
]
},
{
"featureType": "water",
"elementType": "geometry",
"stylers": [
{
"color": "#e9e9e9"
},
{
"lightness": 17
}
]
}
];
export default mapStyle;
export default GoogleApiWrapper({
apiKey: ('key')
})(MapContainer);
//Owner article - https://engineering.universe.com/building-a-google-map-in-react-b103b4ee97f1
import React, { Component, createRef } from 'react'
class GoogleMap extends Component {
googleMapRef = React.createRef()
componentDidMount() {
const googleMapScript = document.createElement('script')
googleScript.src = `https://maps.googleapis.com/maps/api/js?key=${GOOGLE_MAP_API_KEY}&libraries=places`
window.document.body.appendChild(googleScript)
googleScript.addEventListener('load', {
this.googleMap = this.createGoogleMap()
this.marker = this.createMarker()
})
}
createGoogleMap = () =>
new window.google.maps.Map(this.googleMapRef.current, {
zoom: 16,
center: {
lat: 43.642567,
lng: -79.387054,
},
disableDefaultUI: true,
})
createMarker = () =>
new window.google.maps.Marker({
position: { lat: 43.642567, lng: -79.387054 },
map: this.googleMap,
})
render() {
return (
<div
id="google-map"
ref={this.googleMapRef}
style={{ width: '400px', height: '300px' }}
/>
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment