├── public
├── favicon.ico
├── manifest.json
└── index.html
├── src
├── App.test.js
├── components
│ ├── MapMarker.js
│ ├── ConstraintSlider.js
│ ├── PlaceCard.js
│ └── MapAutoComplete.js
├── index.css
├── index.js
├── App.js
├── App.css
├── logo.svg
├── serviceWorker.js
└── containers
│ └── MapContainer.js
├── .gitignore
├── README.md
└── package.json
/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/marxlow/google-maps-component-guide/HEAD/public/favicon.ico
--------------------------------------------------------------------------------
/src/App.test.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import ReactDOM from 'react-dom';
3 | import App from './App';
4 |
5 | it('renders without crashing', () => {
6 | const div = document.createElement('div');
7 | ReactDOM.render(, div);
8 | ReactDOM.unmountComponentAtNode(div);
9 | });
10 |
--------------------------------------------------------------------------------
/public/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "short_name": "React App",
3 | "name": "Create React App Sample",
4 | "icons": [
5 | {
6 | "src": "favicon.ico",
7 | "sizes": "64x64 32x32 24x24 16x16",
8 | "type": "image/x-icon"
9 | }
10 | ],
11 | "start_url": ".",
12 | "display": "standalone",
13 | "theme_color": "#000000",
14 | "background_color": "#ffffff"
15 | }
16 |
--------------------------------------------------------------------------------
/src/components/MapMarker.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { Icon } from 'antd';
3 |
4 | const MapMarker = (({ name, key }) => {
5 | return (
6 |
7 | {name}
8 |
9 |
10 | );
11 | });
12 |
13 | export default MapMarker;
14 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2 |
3 | # dependencies
4 | /node_modules
5 | /.pnp
6 | .pnp.js
7 |
8 | # testing
9 | /coverage
10 |
11 | # production
12 | /build
13 |
14 | # misc
15 | .DS_Store
16 | .env.local
17 | .env.development.local
18 | .env.test.local
19 | .env.production.local
20 |
21 | npm-debug.log*
22 | yarn-debug.log*
23 | yarn-error.log*
24 |
--------------------------------------------------------------------------------
/src/index.css:
--------------------------------------------------------------------------------
1 | body {
2 | margin: 0;
3 | padding: 0;
4 | font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen",
5 | "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
6 | sans-serif;
7 | -webkit-font-smoothing: antialiased;
8 | -moz-osx-font-smoothing: grayscale;
9 | }
10 |
11 | code {
12 | font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New",
13 | monospace;
14 | }
15 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ## Welcome
2 | A React web app that integrates with the Google Maps API to find you ice creams.
3 |
4 | 
5 |
6 | ## Setup
7 | Make sure that you have replaced the API_KEY variable in `MapContainer.js` before running the app.
8 |
9 | ## Starting the app
10 |
11 | ### `npm start`
12 |
13 | Runs the app in the development mode.
14 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
15 |
--------------------------------------------------------------------------------
/src/index.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import ReactDOM from 'react-dom';
3 | import './index.css';
4 | import App from './App';
5 | import * as serviceWorker from './serviceWorker';
6 |
7 | ReactDOM.render(, document.getElementById('root'));
8 |
9 | // If you want your app to work offline and load faster, you can change
10 | // unregister() to register() below. Note this comes with some pitfalls.
11 | // Learn more about service workers: https://bit.ly/CRA-PWA
12 | serviceWorker.unregister();
13 |
--------------------------------------------------------------------------------
/src/components/ConstraintSlider.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { Icon, Slider } from 'antd';
3 |
4 | const ConstraintSlider = (({ iconType, value, onChange, text }) => {
5 | return (
6 | < section className="d-flex flex-column" >
7 |
8 |
9 |
10 |
11 | {text}
12 |
13 | );
14 | });
15 |
16 | export default ConstraintSlider;
--------------------------------------------------------------------------------
/src/App.js:
--------------------------------------------------------------------------------
1 | import React, { Component } from 'react';
2 | import logo from './logo.svg';
3 | import MapContainer from './containers/MapContainer';
4 |
5 | // CSS
6 | import './App.css';
7 | import '../node_modules/bootstrap/dist/css/bootstrap.min.css'
8 | import 'antd/dist/antd.css';
9 |
10 | class App extends Component {
11 | render() {
12 | return (
13 |
14 |
15 | {/*
*/}
16 |
17 |
18 |
19 |
20 |
21 | );
22 | }
23 | }
24 |
25 | export default App;
26 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "google-maps-component-guide",
3 | "version": "0.1.0",
4 | "private": true,
5 | "dependencies": {
6 | "antd": "^3.16.2",
7 | "bootstrap": "^4.3.1",
8 | "google-map-react": "^1.1.4",
9 | "react": "^16.8.6",
10 | "react-dom": "^16.8.6",
11 | "react-scripts": "2.1.8"
12 | },
13 | "scripts": {
14 | "start": "react-scripts start",
15 | "build": "react-scripts build",
16 | "test": "react-scripts test",
17 | "eject": "react-scripts eject"
18 | },
19 | "eslintConfig": {
20 | "extends": "react-app"
21 | },
22 | "browserslist": [
23 | ">0.2%",
24 | "not dead",
25 | "not ie <= 11",
26 | "not op_mini all"
27 | ]
28 | }
29 |
--------------------------------------------------------------------------------
/src/components/PlaceCard.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { Rate } from 'antd';
3 |
4 | // TODO: info is bad naming.
5 | const PlaceCard = (({ info, key }) => {
6 | const { address, distanceText, name, openNow, photoUrl, priceLevel, rating, timeText } = info;
7 | return (
8 |
9 |

10 |
11 |
12 |
{name}
13 | {address}
14 | {distanceText}
15 | {timeText}
16 |
17 |
18 | {openNow ?
19 | - Open
20 | :
21 | - Closed
22 | }
23 | - Rating -
24 | - Price -
25 |
26 |
27 |
28 | );
29 | });
30 |
31 | export default PlaceCard;
--------------------------------------------------------------------------------
/src/App.css:
--------------------------------------------------------------------------------
1 | .App {
2 | text-align: center;
3 | background-color: ivory;
4 | height: 100vh;
5 | }
6 |
7 | .App-logo {
8 | animation: App-logo-spin infinite 20s linear;
9 | height: 4rem;
10 | pointer-events: none;
11 | }
12 |
13 | .App-header {
14 | background-color: #282c34;
15 | min-height: 5rem;
16 | display: flex;
17 | flex-direction: column;
18 | align-items: center;
19 | justify-content: center;
20 | font-size: calc(10px + 2vmin);
21 | color: white;
22 | }
23 |
24 | .App-link {
25 | color: #61dafb;
26 | }
27 |
28 | @keyframes App-logo-spin {
29 | from {
30 | transform: rotate(0deg);
31 | }
32 | to {
33 | transform: rotate(360deg);
34 | }
35 | }
36 |
37 | /* SHAME - Bad CSS practices ahead */
38 | /* Custom */
39 | .fw-md {
40 | font-weight: 800 !important;
41 | }
42 |
43 | .h-lg {
44 | height: 35rem;
45 | }
46 |
47 | .font-1-5 {
48 | font-size: 1.5rem;
49 | }
50 |
51 | .image-wrapper-sm {
52 | object-fit: cover;
53 | border-radius: 50%;
54 | height: 15rem;
55 | width: 100%;
56 | }
57 |
58 | /* BOOTSTRAP Overwrites */
59 | .card-title {
60 | color: #ee8301;
61 | }
62 |
63 | /* ANTD Overwrites */
64 | .ant-btn-primary {
65 | background-color: #ee8301 !important;
66 | border-color: #ee8301 !important;
67 | }
68 |
69 | .ant-slider-handle {
70 | border-color: #ee8301 !important;
71 | }
72 |
73 | .ant-slider-track {
74 | background-color: #282c34 !important;
75 | }
76 |
--------------------------------------------------------------------------------
/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
10 |
11 |
15 |
16 |
25 | React App
26 |
27 |
28 |
29 |
30 |
40 |
41 |
42 |
--------------------------------------------------------------------------------
/src/components/MapAutoComplete.js:
--------------------------------------------------------------------------------
1 | import React, { Component } from 'react';
2 | import { AutoComplete } from 'antd';
3 |
4 | class MapAutoComplete extends Component {
5 | constructor(props) {
6 | super(props);
7 | this.state = {
8 | suggestionts: [],
9 | dataSource: [],
10 | singaporeLatLng: this.props.singaporeLatLng,
11 | autoCompleteService: this.props.autoCompleteService,
12 | geoCoderService: this.props.geoCoderService,
13 | }
14 | }
15 |
16 | // Runs after clicking away from the input field or pressing 'enter'.
17 | // Geocode the location selected to be created as a marker.
18 | onSelect = ((value) => {
19 | this.state.geoCoderService.geocode({ address: value }, ((response) => {
20 | const { location } = response[0].geometry;
21 | this.props.addMarker(location.lat(), location.lng(), this.props.markerName);
22 | }))
23 | });
24 |
25 |
26 | // Runs a search on the current value as the user types in the AutoComplete field.
27 | handleSearch = ((value) => {
28 | const { autoCompleteService, singaporeLatLng } = this.state;
29 | // Search only if there is a string
30 | if (value.length > 0) {
31 | const searchQuery = {
32 | input: value,
33 | location: singaporeLatLng, // Search in Singapore
34 | radius: 30000, // With a 30km radius
35 | };
36 | autoCompleteService.getQueryPredictions(searchQuery, ((response) => {
37 | // The name of each GoogleMaps suggestion object is in the "description" field
38 | if (response) {
39 | const dataSource = response.map((resp) => resp.description);
40 | this.setState({ dataSource, suggestions: response });
41 | }
42 | }));
43 | }
44 | });
45 |
46 | render() {
47 | const { dataSource } = this.state;
48 | return (
49 |
56 | );
57 | }
58 | }
59 |
60 | export default MapAutoComplete;
--------------------------------------------------------------------------------
/src/logo.svg:
--------------------------------------------------------------------------------
1 |
8 |
--------------------------------------------------------------------------------
/src/serviceWorker.js:
--------------------------------------------------------------------------------
1 | // This optional code is used to register a service worker.
2 | // register() is not called by default.
3 |
4 | // This lets the app load faster on subsequent visits in production, and gives
5 | // it offline capabilities. However, it also means that developers (and users)
6 | // will only see deployed updates on subsequent visits to a page, after all the
7 | // existing tabs open on the page have been closed, since previously cached
8 | // resources are updated in the background.
9 |
10 | // To learn more about the benefits of this model and instructions on how to
11 | // opt-in, read https://bit.ly/CRA-PWA
12 |
13 | const isLocalhost = Boolean(
14 | window.location.hostname === 'localhost' ||
15 | // [::1] is the IPv6 localhost address.
16 | window.location.hostname === '[::1]' ||
17 | // 127.0.0.1/8 is considered localhost for IPv4.
18 | window.location.hostname.match(
19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
20 | )
21 | );
22 |
23 | export function register(config) {
24 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
25 | // The URL constructor is available in all browsers that support SW.
26 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
27 | if (publicUrl.origin !== window.location.origin) {
28 | // Our service worker won't work if PUBLIC_URL is on a different origin
29 | // from what our page is served on. This might happen if a CDN is used to
30 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374
31 | return;
32 | }
33 |
34 | window.addEventListener('load', () => {
35 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
36 |
37 | if (isLocalhost) {
38 | // This is running on localhost. Let's check if a service worker still exists or not.
39 | checkValidServiceWorker(swUrl, config);
40 |
41 | // Add some additional logging to localhost, pointing developers to the
42 | // service worker/PWA documentation.
43 | navigator.serviceWorker.ready.then(() => {
44 | console.log(
45 | 'This web app is being served cache-first by a service ' +
46 | 'worker. To learn more, visit https://bit.ly/CRA-PWA'
47 | );
48 | });
49 | } else {
50 | // Is not localhost. Just register service worker
51 | registerValidSW(swUrl, config);
52 | }
53 | });
54 | }
55 | }
56 |
57 | function registerValidSW(swUrl, config) {
58 | navigator.serviceWorker
59 | .register(swUrl)
60 | .then(registration => {
61 | registration.onupdatefound = () => {
62 | const installingWorker = registration.installing;
63 | if (installingWorker == null) {
64 | return;
65 | }
66 | installingWorker.onstatechange = () => {
67 | if (installingWorker.state === 'installed') {
68 | if (navigator.serviceWorker.controller) {
69 | // At this point, the updated precached content has been fetched,
70 | // but the previous service worker will still serve the older
71 | // content until all client tabs are closed.
72 | console.log(
73 | 'New content is available and will be used when all ' +
74 | 'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
75 | );
76 |
77 | // Execute callback
78 | if (config && config.onUpdate) {
79 | config.onUpdate(registration);
80 | }
81 | } else {
82 | // At this point, everything has been precached.
83 | // It's the perfect time to display a
84 | // "Content is cached for offline use." message.
85 | console.log('Content is cached for offline use.');
86 |
87 | // Execute callback
88 | if (config && config.onSuccess) {
89 | config.onSuccess(registration);
90 | }
91 | }
92 | }
93 | };
94 | };
95 | })
96 | .catch(error => {
97 | console.error('Error during service worker registration:', error);
98 | });
99 | }
100 |
101 | function checkValidServiceWorker(swUrl, config) {
102 | // Check if the service worker can be found. If it can't reload the page.
103 | fetch(swUrl)
104 | .then(response => {
105 | // Ensure service worker exists, and that we really are getting a JS file.
106 | const contentType = response.headers.get('content-type');
107 | if (
108 | response.status === 404 ||
109 | (contentType != null && contentType.indexOf('javascript') === -1)
110 | ) {
111 | // No service worker found. Probably a different app. Reload the page.
112 | navigator.serviceWorker.ready.then(registration => {
113 | registration.unregister().then(() => {
114 | window.location.reload();
115 | });
116 | });
117 | } else {
118 | // Service worker found. Proceed as normal.
119 | registerValidSW(swUrl, config);
120 | }
121 | })
122 | .catch(() => {
123 | console.log(
124 | 'No internet connection found. App is running in offline mode.'
125 | );
126 | });
127 | }
128 |
129 | export function unregister() {
130 | if ('serviceWorker' in navigator) {
131 | navigator.serviceWorker.ready.then(registration => {
132 | registration.unregister();
133 | });
134 | }
135 | }
136 |
--------------------------------------------------------------------------------
/src/containers/MapContainer.js:
--------------------------------------------------------------------------------
1 | import React, { Component } from 'react';
2 | import GoogleMapReact from 'google-map-react';
3 | import MapAutoComplete from '../components/MapAutoComplete';
4 | import MapMarker from '../components/MapMarker';
5 | import PlaceCard from '../components/PlaceCard';
6 | import ConstraintSlider from '../components/ConstraintSlider';
7 |
8 | import { Button, Input, Divider, message } from 'antd';
9 |
10 | const SG_COOR = { lat: 1.3521, lng: 103.8198 };
11 |
12 | class MapsContainer extends Component {
13 | constructor(props) {
14 | super(props);
15 | this.state = {
16 | constraints: [{ name: '', time: 0 }],
17 | searchResults: [],
18 | mapsLoaded: false,
19 | markers: [],
20 | map: {},
21 | mapsApi: {},
22 | singaporeLatLng: {},
23 | autoCompleteService: {},
24 | placesService: {},
25 | geoCoderService: {},
26 | directionService: {},
27 | };
28 | }
29 |
30 | // Update name for constraint with index === key
31 | updateConstraintName = ((event, key) => {
32 | event.preventDefault();
33 | const prevConstraints = this.state.constraints;
34 | const constraints = Object.assign([], prevConstraints);
35 | constraints[key].name = event.target.value;
36 | this.setState({ constraints });
37 | });
38 |
39 | // Updates distance (in KM) for constraint with index == key
40 | updateConstraintTime = ((key, value) => {
41 | const prevConstraints = this.state.constraints;
42 | const constraints = Object.assign([], prevConstraints);
43 | constraints[key].time = value;
44 | this.setState({ constraints });
45 | });
46 |
47 | // Adds a Marker to the GoogleMaps component
48 | addMarker = ((lat, lng, name) => {
49 | const prevMarkers = this.state.markers;
50 | const markers = Object.assign([], prevMarkers);
51 |
52 | // If name already exists in marker list just replace lat & lng.
53 | let newMarker = true;
54 | for (let i = 0; i < markers.length; i++) {
55 | if (markers[i].name === name) {
56 | newMarker = false;
57 | markers[i].lat = lat;
58 | markers[i].lng = lng;
59 | message.success(`Updated "${name}" Marker`);
60 | break;
61 | }
62 | }
63 | // Name does not exist in marker list. Create new marker
64 | if (newMarker) {
65 | markers.push({ lat, lng, name });
66 | message.success(`Added new "${name}" Marker`);
67 | }
68 |
69 | this.setState({ markers });
70 | });
71 |
72 | // Runs once when the Google Maps library is ready
73 | // Initializes all services that we need
74 | apiHasLoaded = ((map, mapsApi) => {
75 | this.setState({
76 | mapsLoaded: true,
77 | map,
78 | mapsApi,
79 | singaporeLatLng: new mapsApi.LatLng(SG_COOR.lat, SG_COOR.lng),
80 | autoCompleteService: new mapsApi.places.AutocompleteService(),
81 | placesService: new mapsApi.places.PlacesService(map),
82 | geoCoderService: new mapsApi.Geocoder(),
83 | directionService: new mapsApi.DirectionsService(),
84 | });
85 | });
86 |
87 | // With the constraints, find some places serving ice-cream
88 | handleSearch = (() => {
89 | const { markers, constraints, placesService, directionService, mapsApi } = this.state;
90 | if (markers.length === 0) {
91 | message.warn('Add a constraint and try again!');
92 | return;
93 | }
94 | const filteredResults = [];
95 | const marker = markers[0];
96 | const timeLimit = constraints[0].time;
97 | const markerLatLng = new mapsApi.LatLng(marker.lat, marker.lng);
98 |
99 | const placesRequest = {
100 | location: markerLatLng,
101 | // radius: '30000', // Cannot be used with rankBy. Pick your poison!
102 | type: ['restaurant', 'cafe'], // List of types: https://developers.google.com/places/supported_types
103 | query: 'ice cream',
104 | rankBy: mapsApi.places.RankBy.DISTANCE, // Cannot be used with radius.
105 | };
106 |
107 | // First, search for ice cream shops.
108 | placesService.textSearch(placesRequest, ((response) => {
109 | // Only look at the nearest top 5.
110 | const responseLimit = Math.min(5, response.length);
111 | for (let i = 0; i < responseLimit; i++) {
112 | const iceCreamPlace = response[i];
113 | const { rating, name } = iceCreamPlace;
114 | const address = iceCreamPlace.formatted_address; // e.g 80 mandai Lake Rd,
115 | const priceLevel = iceCreamPlace.price_level; // 1, 2, 3...
116 | let photoUrl = '';
117 | let openNow = false;
118 | if (iceCreamPlace.opening_hours) {
119 | openNow = iceCreamPlace.opening_hours.open_now; // e.g true/false
120 | }
121 | if (iceCreamPlace.photos && iceCreamPlace.photos.length > 0) {
122 | photoUrl = iceCreamPlace.photos[0].getUrl();
123 | }
124 |
125 | // Second, For each iceCreamPlace, check if it is within acceptable travelling distance
126 | const directionRequest = {
127 | origin: markerLatLng,
128 | destination: address, // Address of ice cream place
129 | travelMode: 'DRIVING',
130 | }
131 | directionService.route(directionRequest, ((result, status) => {
132 | if (status !== 'OK') { return }
133 | const travellingRoute = result.routes[0].legs[0]; // { duration: { text: 1mins, value: 600 } }
134 | const travellingTimeInMinutes = travellingRoute.duration.value / 60;
135 | if (travellingTimeInMinutes < timeLimit) {
136 | const distanceText = travellingRoute.distance.text; // 6.4km
137 | const timeText = travellingRoute.duration.text; // 11 mins
138 | filteredResults.push({
139 | name,
140 | rating,
141 | address,
142 | openNow,
143 | priceLevel,
144 | photoUrl,
145 | distanceText,
146 | timeText,
147 | });
148 | }
149 | // Finally, Add results to state
150 | this.setState({ searchResults: filteredResults });
151 | }));
152 | }
153 | }));
154 | });
155 |
156 | render() {
157 | const { constraints, mapsLoaded, singaporeLatLng, markers, searchResults } = this.state;
158 | const { autoCompleteService, geoCoderService } = this.state; // Google Maps Services
159 | return (
160 |
161 |
Find Some Ice-Creams!
162 | {/* Constraints section */}
163 |
164 | {mapsLoaded ?
165 |
166 | {constraints.map((constraint, key) => {
167 | const { name, time } = constraint;
168 | return (
169 |
170 |
171 | this.updateConstraintName(event, key)} />
172 |
179 |
180 |
this.updateConstraintTime(key, value)}
184 | text="Minutes away by car"
185 | />
186 |
187 |
188 | );
189 | })}
190 |
191 | : null
192 | }
193 |
194 |
195 | {/* Maps Section */}
196 |
197 | this.apiHasLoaded(map, maps)} // "maps" is the mapApi. Bad naming but that's their library.
206 | >
207 | {/* Pin markers on the Map*/}
208 | {markers.map((marker, key) => {
209 | const { name, lat, lng } = marker;
210 | return (
211 |
212 | );
213 | })}
214 |
215 |
216 |
217 | {/* Search Button */}
218 |
219 |
220 | {/* Results section */}
221 | {searchResults.length > 0 ?
222 | <>
223 |
224 |
225 |
226 |
Tadah! Ice-Creams!
227 |
228 | {searchResults.map((result, key) => (
229 |
230 | ))}
231 |
232 |
233 |
234 | >
235 | : null}
236 |
237 | )
238 | }
239 | }
240 |
241 | export default MapsContainer;
--------------------------------------------------------------------------------