{"id":1403,"date":"2020-08-14T16:37:36","date_gmt":"2020-08-14T16:37:36","guid":{"rendered":"https:\/\/lvboard.infostore.in.ua\/?p=1403"},"modified":"2020-08-14T16:37:36","modified_gmt":"2020-08-14T16:37:36","slug":"a-practical-guide-to-integrating-google-maps-in-react","status":"publish","type":"post","link":"https:\/\/lvboard.infostore.in.ua\/?p=1403","title":{"rendered":"A practical guide to integrating Google Maps in React"},"content":{"rendered":"\n<p>There\u2019s a quote from&nbsp;<a href=\"https:\/\/en.wikipedia.org\/wiki\/Clarke%27s_three_laws\">British science-fiction writer Arthur Charles Clarke<\/a>&nbsp;that goes, \u201cAny sufficiently advanced technology is indistinguishable from magic.\u201d<\/p>\n\n\n\n<!--more-->\n\n\n\n<p>We might take it for granted, but Google Maps is a modern miracle in many respects. The possibilities it allows for are endless and can provide real value to your business and users. From showing your office location to showing a route a package delivery will take, Google Maps is flexible and powerful enough to handle a wide variety of use cases.<\/p>\n\n\n\n<p>Indeed, there are a number of reasons why you may choose to integrate Google Maps into your React app, and we\u2019ll be taking a look at one of the most popular ones: displaying your business address. You can then use this as a base for other, more complex cases if you desire.<\/p>\n\n\n\n<p>Because of how incredibly powerful and complex Google Maps is, we\u2019ll need the aptly named google-map-react package to help us integrate it into our React app. This package is a component written over a small set of the Google Maps API, and it allows you to render any React component on the Google Map. It is actively maintained and simple enough to use that it is my default go-to for integrating Google Maps in a React project.<\/p>\n\n\n\n<p>Before we start building, however, I feel it would be a good idea to list some reasons why you may want to put Google Maps on your website (or web app):<\/p>\n\n\n\n<ul><li>To provide directions to your business address<\/li><li>To show a route to an event (i.e., a concert or conference)<\/li><li>To provide live updates on a shipped item\u2019s location<\/li><li>Showcase interesting places around the world<\/li><li>etc\u2026<\/li><\/ul>\n\n\n\n<p>This is just a small list of features made possible by the Google maps API, and you may have other business requirements. For this guide, we\u2019ll build a contact page that contains a map displaying the address of the business, as this is the most common use case I\u2019ve encountered. The google-map-react team has provided a&nbsp;<a href=\"https:\/\/github.com\/google-map-react\/google-map-react#examples\">list of examples<\/a>&nbsp;you can go through in case you require something a bit more advanced.<\/p>\n\n\n\n<h2>Requirements to follow along<\/h2>\n\n\n\n<p>If you would like to code along with me, you\u2019ll need the following:<\/p>\n\n\n\n<ol><li>A React application set up<\/li><li>A Google Maps API key (it\u2019s free)<\/li><li>Ten minutes of your time<\/li><\/ol>\n\n\n\n<p>I have set up a sample repository that you can clone to follow along. Run the following command to clone the repo to your local machine:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">git clone https:\/\/github.com\/ovieokeh\/contact-page-with-google-maps.git<\/pre>\n\n\n\n<p>After cloning, run&nbsp;<code>npm install<\/code>&nbsp;to install all the project dependencies, then run&nbsp;<code>npm run start<\/code>&nbsp;to open the project in a new tab. You should see a sample contact page without Google Maps integrated. For the rest of the tutorial, we\u2019ll create a React component to hold the Google Map and embed it into the contact page.<\/p>\n\n\n\n<p>As for the Google Maps API key, you can get one for free by following&nbsp;<a href=\"https:\/\/developers.google.com\/maps\/documentation\/javascript\/get-api-key\">the instructions on the Google Maps documentation<\/a>. Note that you will need to set up a billing account to get rid of the limitations and watermark that comes with it.<\/p>\n\n\n\n<p>Once you have all these ready, we can start building. The final version of what we\u2019ll be building looks like this:<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter\"><img src=\"https:\/\/i2.wp.com\/blog.logrocket.com\/wp-content\/uploads\/2020\/06\/finished-sample-project.png?resize=730%2C820&amp;ssl=1\" alt=\"How Our FInished Sample Project Should Look\" class=\"wp-image-19927\"\/><\/figure><\/div>\n\n\n\n<h2 id=\"integratinggooglemaps\">Integrating Google Maps<\/h2>\n\n\n\n<p>To reiterate, I will not go through all the code for the contact page, as this article is focused mainly on integrating Google Map into a React project. Here are the steps we\u2019re going to follow:<\/p>\n\n\n\n<ol><li>Create a React component to hold the map (<code>Map.jsx<\/code>)<\/li><li>Create another React component to mark the address on the map (<code>LocationPin.jsx<\/code>)<\/li><li>Embed the map component into the contact page<\/li><\/ol>\n\n\n\n<h3><code>Map.jsx<\/code><\/h3>\n\n\n\n<pre class=\"wp-block-preformatted\">mkdir src\/components\/map &amp;&amp; touch src\/components\/Map.jsx<\/pre>\n\n\n\n<p>Run the command above to create a new file in the&nbsp;<code>\/components<\/code>&nbsp;folder. Inside this file, we\u2019ll write the code for the map component and the address pin. Before we start writing any code, though, we have to install the google-map-react package by running the following command:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">yarn add google-map-react<\/pre>\n\n\n\n<p>After installing the package, we\u2019ll also need something else: the coordinates of our business address. This means a quick Google search for the longitude and latitude values of your business address. I\u2019m using Google\u2019s Amphitheatre address, so I did a quick search and got the following values:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">const location = {\n  address: '1600 Amphitheatre Parkway, Mountain View, california.',\n  lat: 37.42216,\n  lng: -122.08427,\n}<\/pre>\n\n\n\n<p>The values will be different for your address, of course. Store the values in the object as shown above, and we pass these values to the&nbsp;<code>Map<\/code>&nbsp;component so we can render a pin on the map. So, to recap, you\u2019ll need the following data:<\/p>\n\n\n\n<ol><li>Google Map API Key<\/li><li><code>google-map-react<\/code>&nbsp;installed<\/li><li>Longitude and latitude values for your business address<\/li><\/ol>\n\n\n\n<p>Since we have all these data, we can go ahead and start building out the&nbsp;<code>Map<\/code>&nbsp;component. If you want to see the final code, you can check out the&nbsp;<code>add-map<\/code>&nbsp;branch on the repo you cloned earlier, otherwise, continue with the tutorial to learn how to build it yourself.<\/p>\n\n\n\n<p>Still inside&nbsp;<code>src\/components\/map\/Map.jsx<\/code>, import React, the&nbsp;<code>google-map-package<\/code>, and the corresponding CSS like so:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">import React from 'react'\nimport GoogleMapReact from 'google-map-react'\nimport '.\/map.css'<\/pre>\n\n\n\n<p>You can get the contents of&nbsp;<code>map.css<\/code>&nbsp;<a href=\"https:\/\/github.com\/ovieokeh\/contact-page-with-google-maps\/blob\/add-map\/src\/components\/map\/map.css\">from the repo here.<\/a><\/p>\n\n\n\n<p>Create a new&nbsp;<code>Map<\/code>&nbsp;component that takes in two props like so:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">const Map = ({ location, zoomLevel }) =&gt; (\n  &lt;div className=\"map\"&gt;\n    &lt;h2 className=\"map-h2\"&gt;Come Visit Us At Our Campus&lt;\/h2&gt;\n\n    &lt;div className=\"google-map\"&gt;\n      &lt;GoogleMapReact\n        bootstrapURLKeys={{ key: '' }}\n        defaultCenter={location}\n        defaultZoom={zoomLevel}\n      &gt;\n        &lt;LocationPin\n          lat={location.lat}\n          lng={location.lng}\n          text={location.address}\n        \/&gt;\n      &lt;\/GoogleMapReact&gt;\n    &lt;\/div&gt;\n  &lt;\/div&gt;\n)<\/pre>\n\n\n\n<p>Can you guess what the&nbsp;<code>location<\/code>&nbsp;prop is? It\u2019s the object we created earlier that holds the address, latitude, and longitude values of the location.&nbsp;<code>zoomLevel<\/code>&nbsp;is an integer from 0\u201320 that determines&nbsp;<a href=\"https:\/\/developers.google.com\/maps\/documentation\/javascript\/interaction#zoom\">the scale of the map when rendered on the screen<\/a>.<\/p>\n\n\n\n<p>You\u2019ll notice that the&nbsp;<code>GoogleMapReact<\/code>&nbsp;component takes in a child,&nbsp;<code>LocationPin<\/code>, but do note that it can take in any number of children.&nbsp;<code>LocationPin<\/code>&nbsp;will render the&nbsp;<code>text<\/code>&nbsp;prop on top of the map at the location we specify with the&nbsp;<code>lat<\/code>&nbsp;and&nbsp;<code>lng<\/code>&nbsp;props. We\u2019ll create this component in the next section.<\/p>\n\n\n\n<p>Now let\u2019s examine the props being passed to the&nbsp;<code>GoogleMapReact<\/code>&nbsp;component to understand what each one does:<\/p>\n\n\n\n<ol><li><code>bootstrapURLKeys<\/code>&nbsp;is an object that holds the API key you copied from your Google Console. Now you can hardcode the key here, but that is not recommended for code that gets committed to GitHub or is otherwise publicly accessible. You can check out&nbsp;<a href=\"https:\/\/www.freecodecamp.org\/forum\/t\/keeping-api-key-hidden-using-react\/272539\">this discussion on how to secure your API keys on the client<\/a>.<\/li><li><code>defaultCenter<\/code>&nbsp;is simply the center of the map when it loads for the first time.<\/li><li><code>defaultZoom<\/code>&nbsp;defines the initial scale of the map.<\/li><\/ol>\n\n\n\n<p>This alone is enough to render a bare-bones map on the screen, but we need to do something else before we can render this component. We need to write the code for&nbsp;<code>LocationPin<\/code>.<\/p>\n\n\n\n<h3><code>LocationPin<\/code><\/h3>\n\n\n\n<figure class=\"wp-block-image\" id=\"attachment_19928\"><img src=\"https:\/\/i1.wp.com\/blog.logrocket.com\/wp-content\/uploads\/2020\/06\/locationpin-example.png?resize=730%2C407&amp;ssl=1\" alt=\"The LocationPin Rendered On The Map\" class=\"wp-image-19928\"\/><figcaption>LocationPin can mark wherever we want on the map.<\/figcaption><\/figure>\n\n\n\n<p>We want a way to call users\u2019 attention to a specific location on the map. Since google-map-react allows us to render any React component on the map, we can create a simple component that displays a pin icon and text.<\/p>\n\n\n\n<p>For the icon, I\u2019ll be using the Iconify library, which is a collection of free svg icons. Still inside the same file we\u2019ve been working in, import the following packages like so:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">import { Icon } from '@iconify\/react'\nimport locationIcon from '@iconify\/icons-mdi\/map-marker'<\/pre>\n\n\n\n<p>Then go ahead and define the&nbsp;<code>LocationPin<\/code>&nbsp;component like so:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">const LocationPin = ({ text }) =&gt; (\n  &lt;div className=\"pin\"&gt;\n    &lt;Icon icon={locationIcon} className=\"pin-icon\" \/&gt;\n    &lt;p className=\"pin-text\"&gt;{text}&lt;\/p&gt;\n  &lt;\/div&gt;\n)<\/pre>\n\n\n\n<p>I\u2019m sure this component is pretty self-explanatory. Note that the styling for&nbsp;<code>LocationPin<\/code>&nbsp;is already included in&nbsp;<code>map.css<\/code>, but you can style it however you like.<\/p>\n\n\n\n<p>We\u2019re actually done with this tutorial. All we need to do now is export the&nbsp;<code>Map<\/code>&nbsp;component and include it in the contact page. At the bottom of the file, export the&nbsp;<code>Map<\/code>&nbsp;component like so:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">export default Map<\/pre>\n\n\n\n<h3>Using the&nbsp;<code>Map<\/code>&nbsp;component<\/h3>\n\n\n\n<p>Now since the&nbsp;<code>Map<\/code>&nbsp;component is just a React component, we can go ahead and use it anywhere we like. Open&nbsp;<code>src\/App.jsx<\/code>, import the Map component, and include it between&nbsp;<code>ContactSection<\/code>&nbsp;and&nbsp;<code>DisclaimerSection<\/code>, like so:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">import React from 'react'\n\nimport IntroSection from '.\/components\/intro\/Intro'\nimport ContactSection from '.\/components\/contact-section\/ContactSection'\nimport MapSection from '.\/components\/map\/Map' \/\/ import the map here\nimport DisclaimerSection from '.\/components\/disclaimer\/Disclaimer'\nimport FooterSection from '.\/components\/footer\/Footer'\n\nimport '.\/app.css'\n\nconst location = {\n  address: '1600 Amphitheatre Parkway, Mountain View, california.',\n  lat: 37.42216,\n  lng: -122.08427,\n} \/\/ our location object from earlier\n\nconst App = () =&gt; (\n  &lt;div className=\"App\"&gt;\n    &lt;IntroSection \/&gt;\n    &lt;ContactSection \/&gt;\n    &lt;MapSection location={location} zoomLevel={17} \/&gt; {\/* include it here *\/}\n    &lt;DisclaimerSection \/&gt;\n    &lt;FooterSection \/&gt;\n  &lt;\/div&gt;\n)\n\nexport default App<\/pre>\n\n\n\n<p>Now start the project by running&nbsp;<code>yarn start<\/code>&nbsp;in your terminal and navigate to&nbsp;<code>localhost:3000<\/code>. You should see your contact page with a nice-looking map that pinpoints your business address. Pretty nifty, right?<\/p>\n\n\n\n<h2>Conclusion<\/h2>\n\n\n\n<p>With fewer than 100 lines of code, we\u2019ve been able to integrate Google Maps to display our office location along with a visual marker to pinpoint the address. This is a basic example of what you can accomplish with google-map-react.<\/p>\n\n\n\n<p>There are&nbsp;<a href=\"https:\/\/github.com\/google-map-react\/google-map-react#examples\">more examples on their documentation<\/a>&nbsp;for use cases that are a bit more advanced than this fairly simple one. I hope this tutorial was helpful to you, and happy coding&nbsp;<img alt=\"\u2764\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/13.0.0\/svg\/2764.svg\">.<\/p>\n\n\n\n<h2>Full visibility into production React apps<\/h2>\n\n\n\n<p>Debugging React applications can be difficult, especially when users experience issues that are difficult to reproduce. If you\u2019re interested in monitoring and tracking Redux state, automatically surfacing JavaScript errors, and tracking slow network requests and component load time,&nbsp;<a href=\"https:\/\/www2.logrocket.com\/react-performance-monitoring\">try LogRocket<\/a>.&nbsp;<a href=\"https:\/\/www2.logrocket.com\/react-performance-monitoring\" target=\"_blank\" rel=\"noreferrer noopener\"><\/a><a href=\"https:\/\/www2.logrocket.com\/react-performance-monitoring\" target=\"_blank\" rel=\"noreferrer noopener\"><\/a><\/p>\n\n\n\n<p><a href=\"https:\/\/www2.logrocket.com\/react-performance-monitoring\" target=\"_blank\" rel=\"noreferrer noopener\">LogRocket<\/a>&nbsp;is like a DVR for web apps, recording literally everything that happens on your React app. Instead of guessing why problems happen, you can aggregate and report on what state your application was in when an issue occurred. LogRocket also monitors your app&#8217;s performance, reporting with metrics like client CPU load, client memory usage, and more.<\/p>\n\n\n\n<p>The LogRocket Redux middleware package adds an extra layer of visibility into your user sessions. LogRocket logs all actions and state from your Redux stores.<\/p>\n\n\n\n<p>Modernize how you debug your React apps \u2014&nbsp;<a href=\"https:\/\/www2.logrocket.com\/react-performance-monitoring\" target=\"_blank\" rel=\"noreferrer noopener\">start monitoring for free<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>There\u2019s a quote from&nbsp;British science-fiction writer Arthur Charles Clarke&nbsp;that goes, \u201cAny sufficiently advanced technology is indistinguishable from magic.\u201d<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[30],"tags":[65],"_links":{"self":[{"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=\/wp\/v2\/posts\/1403"}],"collection":[{"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=1403"}],"version-history":[{"count":1,"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=\/wp\/v2\/posts\/1403\/revisions"}],"predecessor-version":[{"id":1404,"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=\/wp\/v2\/posts\/1403\/revisions\/1404"}],"wp:attachment":[{"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=1403"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=1403"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=1403"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}