Implement Google Maps in ReactJs

Written by mchisti | Published 2017/10/05
Tech Story Tags: react | google | google-maps | api | programming

TLDRvia the TL;DR App

I’ve had my fair share of trouble implementing Google Maps in ReactJs using a npm package. Hopefully this article helps you avoid the troubles I’ve gone through.

Finding the Best Package

The trouble was mostly finding the best package with good documentation to follow through so that I can get my Google Maps on my page and going. The package I found best was google-map-react by istarkov.

Google Map Example Project

What was really nice of him to also do, was to also create a React.Js example project implementing google-map-react. This way you can have real world application to see an example of.

Quick Start

He does a pretty good job getting you quickly started through his documentation, but I threw in this example just in case you wanted to copy and paste it immediately.

While in your current React.JS directory, run the following lines of code in your terminal.

npm i -S google-map-react

Then create a component, I’m going to call mine map.js. Copy and paste the following lines of code to that file.

import React, { Component } from 'react'import GoogleMapReact from 'google-map-react'

const AnyReactComponent = ({ text }) => <div>{ text }</div>;

export default class Map extends Component {static defaultProps = {center: { lat: 40.7446790, lng: -73.9485420 },zoom: 11}

render() {return (<div className='google-map'><GoogleMapReactdefaultCenter={ this.props.center }defaultZoom={ this.props.zoom }><AnyReactComponentlat={ 40.7473310 }lng={ -73.8517440 }text={ 'Where's Waldo?' }/></GoogleMapReact></div>)}}

Now you can just import this file onto any other component/container file you have and it should display Google’s Map in your project! For more understanding of Google Maps, I’d recommend reading the google-map-react GitHub repo with the Google Maps API documentation while using the project as a reference.

Hope this helped!


Published by HackerNoon on 2017/10/05