More

    React Google Maps: How to Integrate Google Maps API

    An Introduction to Integrating React with Google Maps:

    Google maps is a modern-day miracle and a blessing for almost everyone. The app developed by google is a web mapping service that offers features like satellite mapping, aerial photography, street maps, 360’ interactive and panoramic street views, real time traffic conditions and route planning to travel by foot, two-wheeler, cars, trains, air and buses. The main reason this app is loved by one and all is that the app is free and extremely accurate. The benefits of react integrating with google maps are endless and it provides real values for business and personal users by providing accurate office locations and routes that show how long package delivery would take.

     

    How is integrating the google maps API to React beneficial?

     

    • Integrating the Google Maps API with your React components, enables you to display maps on your website. 
    • It helps provide directions to your business address and makes it easier to locate. 
    • It helps us find a route to an event/concert

     

    Requirements/ Prerequisites for integrating Google Maps API with React

     

    • A React application to set up google maps with
    • A basic familiarity with React Javascript framework
    • API key for google maps (It is available for free and can be obtained easily by following all the instructions on Google Maps Documentation.)

     

    Install the Google Map Library 

    Before we begin installation, we need the Library called Google Maps React. This is the google map library for react and we can install all dependencies by running the code- 

     

    $ npm install –save google-maps-react

     

    Sample Repository- 

    Before beginning, we need to set up a sample repository 

     

    git clone https://github.com/ovieokeh/contact-page-with-google-maps.git 

     

    Run the above mentioned command to get a clone of the existing repository in your local computer device. 

    Creating a configuration file- 

    The first step to integrating the Google Maps API to the react apps is creating the config.js file. 

    This file contains all the important details like the longitudes, latitudes, zoom levels, and the Google Map API Key. 

    All the above mentioned parameters are essential to the creation of the config.js file and you must have them in order to start with the process. You can add other parameters that you feel are important to the configuration of your map but these are the main ones. 

     

    export default {
        zoomLevel: 16,
        latitudeForFocusingMap: 51.4934,
        longitudeForFocusingMap: 0.0098,
        markerLongitude: 51.4934,
        markerLatitude: 0.0098,
        apiKey: ‘your api key’,
        useDefaultUI: false,
        googleMapsMarkerIcon: ‘marker icon link’
    };

     

    It is important to remember that if you want to post the whole project to a public website or a public space, it is important that you hide the configuration file, especially the apiKey. 

    If you want to push the file to git, just add your config.js file to the .gitignore file and proceed with the process of integration. 

     

    The terms in the code mean the following things- 
    1. Zoom Level- This specifies the initial level, or the level of zoom at which your destination appears on the map as soon as the search results are derived and the map loads. 
    2. latitudeForFocusingMap and longitudeForFocusingMap determine the initial location where the destination is shown as soon as the map loads. 
    3. marker Longitude and markerLatitude are commands that help specify the positions of the markers on the map, if you chose to add any. 
    4. apiKey  is the initial Google Maps API that you were asked to obtain in the beginning. This key allows you to access and use the google maps application. It is pertinent that you hide the key from everyone. 
    5. useDefaultUI This setting is true by default as changing it to false will hide the settings. This is the setting for the map surrounding buttons like the zoom level buttons, fullScreenMode button, Map and Satellite option buttons and the 360 view button. 
    6. googleMapsMarkerIcon is the image icon for your google maps marker. This is red in colour by default and can be customised later.

    Creating the main MapComponent 

     

    import React, { useState } from ‘react’;
    import { Map, GoogleApiWrapper } from ‘google-maps-react’;
    import mapStyles from ‘./mapStyle’;
    import config from ‘../../../../../config’;
    function MapComponent(props) {
      const [zoomLevel, setZoomLevel] = useState(config.zoomLevel)
      const [lat, setLat] = useState(config.lat || 51.4934);
      const [lng, setLng] = useState(config.lng || 0.0098);
      
      return (
        <div className=‘map’>
          <Map
            google={props.google}
            zoom={zoomLevel}
            styles={mapStyles}
            disableDefaultUI={config.useDefaultUI}
            initialCenter={{
              lat,
              lng
            }}
          >
            <Marker
              position={{ lat: config.latitudeForMarker, lng: config.longitudeForMarker }}
              icon={config.googleMapsMarkerIcon}
            />
          </Map>
        </div>
      );
    };
    export default GoogleApiWrapper({ apiKey: config.apiKey })(MapComponent);

     

    The lines from 7 to 9 specify some of the configurations we set and then pass them to the map. You can pass the details directly from the config.js, but for more flexibility, it is better to do it this way. 

    It is important to specify the default latitude and longitude parameters because if we do not do so, the map will not show any definite results. 

     

    Marker is the component that as the name suggests, shows the marker on the map. We give it’s coordinates and a custom icon (optional) and it appears on the map. You can pass off many markers as children to the Map component. 

     

    Other than markers, we can also add Infowindows which can show some information when you select a specific marker. 

     

    import React, { useState } from ‘react’;
    import { Map, GoogleApiWrapper } from ‘google-maps-react’;
    import mapStyles from ‘./mapStyle’;
    import config from ‘../../../../../config’;
    function MapComponent(props) {
      const [zoomLevel, setZoomLevel] = useState(config.zoomLevel);
      const [lat, setLat] = useState(config.lat || 51.4934);
      const [lng, setLng] = useState(config.lng || 0.0098);
      const [state, setState] = useState({
        activeMarker: {},
        showingInfoWindow: false,
        text:
      });
      
      const onMarkerClick = (props, marker) => {
        setState({
          …state,
          activeMarker: marker,
          showingInfoWindow: true,
          text: marker.text ||
        });
      };
      const onInfoWindowClose = () => {
        setState({
          activeMarker: null,
          showingInfoWindow: false
        });
      }
      
      return (
        <div className=‘map’>
          <Map
            google={props.google}
            zoom={zoomLevel}
            styles={mapStyles}
            disableDefaultUI={config.useDefaultUI}
            initialCenter={{
              lat,
              lng
            }}
          >
            <Marker
              position={{ lat: config.latitudeForMarker, lng: config.longitudeForMarker }}
              icon={config.googleMapsMarkerIcon}
              onClick={onMarkerClick}
              text=‘some text’
            />
            <InfoWindow
              marker={state.activeMarker}
              onClose={onInfoWindowClose}
              visible={state.showingInfoWindow}>
              <div>
                <p>{state.text}</p>
              </div>
            </InfoWindow>
          </Map>
        </div>
      );
    };
    • You can see two methods to do this above. One is the onMarkerClick and the other is the onInfoWindowClose. 

    We use the onMarkerClick when a user clicks on the Marker and the method takes the text that will be shown on the infoWindow, that is the marker reference and sets it to state. 

    If you switch to another Marker or click on the close button on the active infoWindow, then the onInforWindowClose method starts and ends the active info window. 

     

    Creating A Custom Style- 

    You can import mapStyles and use it on your maps under the style’s parameter. This sets the basic, custom style for the map. 

     

    The map styles file will look something like this- 

     

    const mapStyles = [
      {
        “elementType”: “geometry”,
        “stylers”: [
          {
            “color”: “#1d2c4d”
          }
        ]
      },
      {
        “elementType”: “labels.text.fill”,
        “stylers”: [
          {
            “color”: “#8ec3b9”
          }
        ]
      },
      {
        “elementType”: “labels.text.stroke”,
        “stylers”: [
          {
            “color”: “#1a3646”
          }
        ]
      },
      {
        “featureType”: “administrative.country”,
        “elementType”: “geometry.stroke”,
        “stylers”: [
          {
            “color”: “#4b6878”
          }
        ]
      },
      {
        “featureType”: “administrative.land_parcel”,
        “elementType”: “labels.text.fill”,
        “stylers”: [
          {
            “color”: “#64779e”
          }
        ]
      },
      {
        “featureType”: “administrative.province”,
        “elementType”: “geometry.stroke”,
        “stylers”: [
          {
            “color”: “#4b6878”
          }
        ]
      },
      {
        “featureType”: “landscape.man_made”,
        “elementType”: “geometry.stroke”,
        “stylers”: [
          {
            “color”: “#334e87”
          }
        ]
      },
      {
        “featureType”: “landscape.natural”,
        “elementType”: “geometry”,
        “stylers”: [
          {
            “color”: “#023e58”
          }
        ]
      },
      {
        “featureType”: “poi”,
        “elementType”: “geometry”,
        “stylers”: [
          {
            “color”: “#283d6a”
          }
        ]
      },
      {
        “featureType”: “poi”,
        “elementType”: “labels.text.fill”,
        “stylers”: [
          {
            “color”: “#6f9ba5”
          }
        ]
      },
      {
        “featureType”: “poi”,
        “elementType”: “labels.text.stroke”,
        “stylers”: [
          {
            “color”: “#1d2c4d”
          }
        ]
      },
      {
        “featureType”: “poi.park”,
        “elementType”: “geometry.fill”,
        “stylers”: [
          {
            “color”: “#023e58”
          }
        ]
      },
      {
        “featureType”: “poi.park”,
        “elementType”: “labels.text.fill”,
        “stylers”: [
          {
            “color”: “#3C7680”
          }
        ]
      },
      {
        “featureType”: “road”,
        “elementType”: “geometry”,
        “stylers”: [
          {
            “color”: “#304a7d”
          }
        ]
      },
      {
        “featureType”: “road”,
        “elementType”: “labels.text.fill”,
        “stylers”: [
          {
            “color”: “#98a5be”
          }
        ]
      },
      {
        “featureType”: “road”,
        “elementType”: “labels.text.stroke”,
        “stylers”: [
          {
            “color”: “#1d2c4d”
          }
        ]
      },
      {
        “featureType”: “road.highway”,
        “elementType”: “geometry”,
        “stylers”: [
          {
            “color”: “#2c6675”
          }
        ]
      },
      {
        “featureType”: “road.highway”,
        “elementType”: “geometry.stroke”,
        “stylers”: [
          {
            “color”: “#255763”
          }
        ]
      },
      {
        “featureType”: “road.highway”,
        “elementType”: “labels.text.fill”,
        “stylers”: [
          {
            “color”: “#b0d5ce”
          }
        ]
      },
      {
        “featureType”: “road.highway”,
        “elementType”: “labels.text.stroke”,
        “stylers”: [
          {
            “color”: “#023e58”
          }
        ]
      },
      {
        “featureType”: “transit”,
        “elementType”: “labels.text.fill”,
        “stylers”: [
          {
            “color”: “#98a5be”
          }
        ]
      },
      {
        “featureType”: “transit”,
        “elementType”: “labels.text.stroke”,
        “stylers”: [
          {
            “color”: “#1d2c4d”
          }
        ]
      },
      {
        “featureType”: “transit.line”,
        “elementType”: “geometry.fill”,
        “stylers”: [
          {
            “color”: “#283d6a”
          }
        ]
      },
      {
        “featureType”: “transit.station”,
        “elementType”: “geometry”,
        “stylers”: [
          {
            “color”: “#3a4762”
          }
        ]
      },
      {
        “featureType”: “water”,
        “elementType”: “geometry”,
        “stylers”: [
          {
            “color”: “#0e1626”
          }
        ]
      },
      {
        “featureType”: “water”,
        “elementType”: “labels.text.fill”,
        “stylers”: [
          {
            “color”: “#4e6d70”
          }
        ]
      }
    ];

     

    You can further customize it and create your own unique style of the map on the https://mapstyle.withgoogle.com/ configurator of maps. 

     

    Recent Articles

    React Ecommerce Templates

      React is the most popular library for the development of e-commerce applications. React eCommerce templates for building eCommerce apps are a combination of several...

    What is React Yarn? How to Install It?

    Introduction to React Yarn The technical community shares hundreds and thousands of pieces of code every day in the community of JavaScript. As a result,...

    React Editor: Features, Installation and Limitations

    Why do we need the react editor?  There is a large range of code-based editors like CodeMirror, Monaco, Ace, etc., that provide us with the...

    React Babel: Everything You Need to Know About It

    Introduction About React Babel: React Babel is a very well known and well-implemented open-source transcompiler of JavaScript. We use it mainly to convert the ECMA...

    React Websocket: Usage, Installation and much more

    Introduction About React Websocket:  If you want to create a long-running connection between a client and a server then use React Websocket. Let's take an...

    Related Stories

    Leave A Reply

    Please enter your comment!
    Please enter your name here

    Stay on op - Ge the daily news in your inbox