Google Maps Javascript Street View Cannot Read Property 'style' of Null

Introduction

Google Maps is a map service provided by Google that supports a broad variety of configuration settings. Calculation Google Maps to your application can provide users with more contextual information than a street accost or ready of coordinates.

This tutorial aims at integrating the Google Maps API into your React components and enabling yous to display maps on your website.

Prerequisites

To complete this tutorial, you volition need:

  • Node.js installed locally, which you can do by following How to Install Node.js and Create a Local Development Environment.
  • Familiarity with the React JavaScript framework.
  • A Google Maps JavasScript API Key.
    • This will crave a Google account, signing into the Google Cloud Platform Console, creating a new projection, and enabling the Google Maps JavasScript API for the project.

Note: To avert the "For development purposes just" messages when using the Google Maps API, you will demand to provide a valid credit carte du jour and associate it with a Billing account for the Google Deject Project, merely it is non required for this tutorial.

This tutorial was verified with Node v14.2.0, npm v6.fourteen.5, react v16.xiii.1, and google-maps-react v.2.0.6.

Footstep i — Setting up a React Awarding

For this tutorial, you are going to utilize create-react-app for scaffolding a new React app.

First, run npx to use create-react-app in a terminal window:

                      
  1. npx create-react-app react-googlemaps

So, navigate to your new project directory:

          cd            react-googlemaps                  

Before y'all add any code, let'southward install your dependencies with:

                      
  1. npm install google-maps-react@ii.0.vi

Note: Optionally, at this point you lot tin remove unnecessary files and imports in your src directory. You will not require logo.svg, App.css, index.css. If yous remove alphabetize.css, you should too remove the import for index.css in alphabetize.html to avoid a build mistake.

At this point, yous accept a React awarding with the google-maps-react library. You tin at present explore using maps in your application.

Pace 2 — Using Map and GoogleApiWrapper

Adjacent, y'all will demand to edit your App.js file and replace the code with your component that will load a Google Map.

Open App.js:

                      
  1. nano src/App.js

Replace the contents of App.js with the following lines of code:

src/App.js

                      import            React,            {            Component            }            from            'react'            ;            import            {            Map,            GoogleApiWrapper            }            from            'google-maps-react'            ;            const            mapStyles            =            {            width            :            '100%'            ,            summit            :            '100%'            }            ;            export            grade            MapContainer            extends            Component            {            render            (            )            {            return            (            <Map         google=            {            this            .props.google}            zoom=            {            xiv            }            style=            {mapStyles}            initialCenter=            {            {            lat            :            -            1.2884            ,            lng            :            36.8233            }            }            /            >            )            ;            }            }            export            default            GoogleApiWrapper            (            {            apiKey            :            'YOUR_GOOGLE_MAPS_API_KEY_GOES_HERE'            }            )            (MapContainer)            ;                  

Note: Replace YOUR_GOOGLE_MAPS_API_KEY_GOES_HERE with your Google Maps JavasScript API Key.

Alert: Be sure to avoid saving your API primal in any files you commit to public repositories (like GitHub) as it can and so be used by others for purposes you did not intend.

For the functionality of a basic Google Map, this is all the lawmaking you need.

The Map component takes in some optional props:

  • style - the CSS style object
  • zoom - number value representing a tighter focus on the map's center
  • initialCenter - an object containing latitude and longitude coordinates

In this example, you are defining:

  • a CSS manner object with 100% width and 100% height
  • a zoom value of xiv
  • and a location of -1.2884, 36.8233 (Kenyatta International Convention Centre in Nairobi, Kenya)

Open up your terminal and run your app:

                      
  1. npm offset

And ensure that the map loads to the browser:

Map displaying in the browser

The GoogleApiWrapper is a Higher-Gild Component (HOC) that provides a wrapper around Google APIs. Alternatively, the GoogleApiWrapper HOC can exist configured by passing a function that will be chosen with the wrapped component'due south props and should render the configuration object like and so:

                      export            default            GoogleApiWrapper            (            (            props            )            =>            (            {            apiKey            :            props.apiKey            }            )            )            (MapContainer)                  

At this bespeak, you have a Google Map in your React application. You lot can now explore implementing other features of Google Maps.

Footstep 3 — Using Markers and InfoWindow

Yous volition now add together a Mark and an InfoWindow to your code.

First, you need to import Marking and InfoWindow components from the google-maps-react library in social club to help you lot reach loading of the two.

src/App.js

                      import            React,            {            Component            }            from            'react'            ;            import            {            Map,            GoogleApiWrapper,            InfoWindow,              Marker            }            from            'google-maps-react'            ;                  

Notice that your component earlier was stateless? You will need to add state for state management.

src/App.js

                      // ...            export            class            MapContainer            extends            Component            {            state              =              {                                      showingInfoWindow              :              simulated              ,                        // Hides or shows the InfoWindow                          activeMarker              :              {              }              ,                        // Shows the active marker upon click                          selectedPlace              :              {              }                        // Shows the InfoWindow to the selected identify upon a marker                          }              ;                        // ...            }                  

Next, you volition need to add outcome handlers for when the Map and the Marker are clicked.

src/App.js

                      // ...            consign            class            MapContainer            extends            Component            {            // ...                          onMarkerClick              =              (              props,                marker,                eastward              )              =>                                      this              .              setState              (              {                                      selectedPlace              :              props,                                      activeMarker              :              marker,                                      showingInfoWindow              :              true                                      }              )              ;                                      onClose              =              props              =>              {                                      if              (              this              .state.showingInfoWindow)              {                                      this              .              setState              (              {                                      showingInfoWindow              :              false              ,                                      activeMarker              :              nothing                                      }              )              ;                                      }                                      }              ;                        // ...            }                  

The onMarkerClick method is used to evidence the InfoWindow, which is a component in the google-maps-react library that gives you the ability for a pop-up window showing details of the clicked Marker.

The onClose method is for closing the InfoWindow once a user clicks on the close button on the InfoWindow.

Allow'due south complete your component past adding <Marker> and <InfoWindow> components to the render method:

src/App.js

                      // ...            export            class            MapContainer            extends            Component            {            // ...            render            (            )            {            render            (            <Map         google=            {            this            .props.google}            zoom=            {            14            }            style=            {mapStyles}            initialCenter=            {            {            lat            :            -            1.2884            ,            lng            :            36.8233            }            }            >                          <Marker            onClick=              {              this              .onMarkerClick}                        name=              {              'Kenyatta International Convention Heart'              }                                      /              >                                      <InfoWindow            marker=              {              this              .land.activeMarker}                        visible=              {              this              .country.showingInfoWindow}                        onClose=              {              this              .onClose}                                      >                                      <div>                                      <h4>              {              this              .state.selectedPlace.name}              <              /h4>                                      <              /div>                                      <              /InfoWindow>                        <            /Map>            )            ;            }            }                  

Run your app:

                      
  1. npm kickoff

And ensure you have the one Marker with the InfoWindow upon click:

Map with Marker and InfoWindow displaying in the browser

As a follow-up do, you lot tin can become and add a few more <Marker>due south on your <Map> and more than interactivity to your <InfoWindow>.

Stride 4 — Displaying the User's Current Location

Y'all will at present fix your map to retrieve the browser'southward electric current location. You will be using Navigator, which is a read-merely belongings that returns a Geolocation object that gives spider web content admission to the location of the device.

In your src directory create a new file and name information technology Map.js:

                      
  1. nano src/Map.js

You will create a component named CurrentLocation — this is where yous will build all the functionality to think your browser's location:

src/Map.js

                      import            React            from            'react'            ;            import            ReactDOM            from            'react-dom'            ;            const            mapStyles            =            {            map            :            {            position            :            'absolute'            ,            width            :            '100%'            ,            height            :            '100%'            }            }            ;            export            class            CurrentLocation            extends            React.Component            {            // ...            }            consign            default            CurrentLocation;                  

You volition begin by calculation some default props to your <CurrentLocation> component, since you will need to set the map with a center in case the current location is not provided. This is handled past the boolean prop centerAroundCurrentLocation:

src/Map.js

                      // ...            CurrentLocation.defaultProps            =            {            zoom            :            14            ,            initialCenter            :            {            lat            :            -            1.2884            ,            lng            :            36.8233            }            ,            centerAroundCurrentLocation            :            false            ,            visible            :            true            }            ;                  

Side by side, you will need to make your component stateful:

src/Map.js

                      // ...            export            class            CurrentLocation            extends            React.Component            {                          constructor              (              props              )              {                                      super              (props)              ;                                      const              {              lat,              lng              }              =              this              .props.initialCenter;                                      this              .state              =              {                                      currentLocation              :              {                                      lat              :              lat,                                      lng              :              lng                          }                                      }              ;                        }            }            // ...                  

Let's too update your <CurrentLocation> component to handle for scenarios when the Google Maps API is non bachelor due to network issues or unexpected maintenance. And too handle situations when the browser'southward current location is provided and recenter the map to that location.

src/Map.js

                      // ...            export            class            CurrentLocation            extends            React.Component            {            // ...                          componentDidUpdate              (              prevProps,                prevState              )              {                                      if              (prevProps.google              !==              this              .props.google)              {                                      this              .              loadMap              (              )              ;                                      }                                      if              (prevState.currentLocation              !==              this              .state.currentLocation)              {                                      this              .              recenterMap              (              )              ;                                      }                        }            }            // ...                  

Let'southward define the recenterMap() office which gets called when the currentLocation in the component's state is updated. Information technology will use the panTo() method to modify the center of the map.

src/Map.js

                      // ...            export            grade            CurrentLocation            extends            React.Component            {            // ...                          recenterMap              (              )              {                                      const              map              =              this              .map;                                      const              electric current              =              this              .state.currentLocation;                                      const              google              =              this              .props.google;                                      const              maps              =              google.maps;                                      if              (map)              {                                      let              heart              =              new              maps.LatLng              (current.lat,              current.lng)              ;                        map.              panTo              (centre)              ;                                      }                                      }                        }            // ...                  

Next, yous will demand to handle the scenario when the map has already loaded. This volition be handled by the componentDidMount() lifecycle method which will set a callback to fetch the current location.

src/Map.js

                      // ...            export            class            CurrentLocation            extends            React.Component            {            // ...                          componentDidMount              (              )              {                                      if              (              this              .props.centerAroundCurrentLocation)              {                                      if              (navigator              &&              navigator.geolocation)              {                        navigator.geolocation.              getCurrentPosition              (              pos              =>              {                                      const              coords              =              pos.coords;                                      this              .              setState              (              {                                      currentLocation              :              {                                      lat              :              coords.latitude,                                      lng              :              coords.longitude                          }                                      }              )              ;                                      }              )              ;                                      }                                      }                                      this              .              loadMap              (              )              ;                                      }                        }            // ...                  

Notice the loadMap() function? Let's go on ahead and define it.

src/Map.js

                      // ...            consign            class            CurrentLocation            extends            React.Component            {            // ...                          loadMap              (              )              {                                      if              (              this              .props              &&              this              .props.google)              {                        // checks if google is available                          const              {              google              }              =              this              .props;                                      const              maps              =              google.maps;                                      const              mapRef              =              this              .refs.map;                        // reference to the actual DOM element                          const              node              =              ReactDOM.              findDOMNode              (mapRef)              ;                                      let              {              zoom              }              =              this              .props;                                      const              {              lat,              lng              }              =              this              .state.currentLocation;                                      const              center              =              new              maps.LatLng              (lat,              lng)              ;                                      const              mapConfig              =              Object.              assign              (                                      {              }              ,                                      {                                      eye              :              heart,                                      zoom              :              zoom                          }                                      )              ;                        // maps.Map() is constructor that instantiates the map                          this              .map              =              new              maps.Map              (node,              mapConfig)              ;                                      }                                      }                        }            // ...                  

The loadMap() function is chosen after the component has been rendered and grabs a reference to the DOM component to where yous desire your map to be placed.

Your <CurrentLocation> component is nearly complete. But you lot demand to ensure that your previous <Marking> picks your current location (i.east., the browser'south current location) and so you need to introduce Parent-Child component communication through the renderChildren() method which will be responsible for calling the method on the kid component.

src/Map.js

                      // ...            export            class            CurrentLocation            extends            React.Component            {            // ...                          renderChildren              (              )              {                                      const              {              children              }              =              this              .props;                                      if              (              !children)              render              ;                                      return              React.Children.              map              (children,              c              =>              {                                      if              (              !c)              render              ;                                      return              React.              cloneElement              (c,              {                                      map              :              this              .map,                                      google              :              this              .props.google,                                      mapCenter              :              this              .land.currentLocation                          }              )              ;                                      }              )              ;                                      }                        }            // ...                  

And finally, let's add your render() method:

src/Map.js

                      // ...            consign            form            CurrentLocation            extends            React.Component            {            // ...                          return              (              )              {                                      const              style              =              Object.              assign              (              {              }              ,              mapStyles.map)              ;                                      return              (                                      <div>                                      <div fashion=              {manner}              ref=              "map"              >                        Loading map...                                      <              /div>                                      {              this              .              renderChildren              (              )              }                                      <              /div>                                      )              ;                                      }                        }            // ...                  

Lastly, yous will need to update your MapContainer component in App.js:

                      
  1. nano src/App.js

Supercede the Map component with your new CurrentLocation component:

src/App.js

                      import            React,            {            Component            }            from            'react'            ;            import            {            GoogleApiWrapper,            InfoWindow,            Marker            }            from            'google-maps-react'            ;                          import              CurrentLocation              from              './Map'              ;                        export            course            MapContainer            extends            Component            {            land            =            {            showingInfoWindow            :            false            ,            activeMarker            :            {            }            ,            selectedPlace            :            {            }            }            ;            onMarkerClick            =            (            props,              marker,              e            )            =>            this            .            setState            (            {            selectedPlace            :            props,            activeMarker            :            marking,            showingInfoWindow            :            true            }            )            ;            onClose            =            props            =>            {            if            (            this            .state.showingInfoWindow)            {            this            .            setState            (            {            showingInfoWindow            :            false            ,            activeMarker            :            null            }            )            ;            }            }            ;            return            (            )            {            return            (                          <CurrentLocation            centerAroundCurrentLocation            google=              {              this              .props.google}                                      >                        <Mark onClick=            {            this            .onMarkerClick}            name=                          {              'Electric current Location'              }                        /            >            <InfoWindow           marker=            {            this            .land.activeMarker}            visible=            {            this            .state.showingInfoWindow}            onClose=            {            this            .onClose}            >            <div>            <h4>            {            this            .land.selectedPlace.name}            <            /h4>            <            /div>            <            /InfoWindow>                          <              /CurrentLocation>                        )            ;            }            }            export            default            GoogleApiWrapper            (            {            apiKey            :            'YOUR_GOOGLE_MAPS_API_KEY_GOES_HERE'            }            )            (MapContainer)            ;                  

Run your app:

          npm start                  

Heading over to your browser, your map should get-go load with your initialCenter and so reload to selection your browser's current location with the Marker positioned to this location, and voilĂ , you are washed:

Map with Current Location displaying in the browser

Conclusion

In this article, y'all were able to load your <Map> React component, add a Mark, and associate an InfoWindow to it. You also made the map display your current location.

Edifice upon this knowledge, you can implement more advanced features such as having polylines and polygons or adding consequence listeners into your maps.

If you'd like to acquire more than about React, take a look at our How To Code in React.js series, or bank check out our React topic folio for exercises and programming projects.

Google Maps Javascript Street View Cannot Read Property 'style' of Null

Source: https://www.digitalocean.com/community/tutorials/how-to-integrate-the-google-maps-api-into-react-applications

0 Response to "Google Maps Javascript Street View Cannot Read Property 'style' of Null"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel