Itsme
Itsme

Reputation: 196

Next.js pages router, how to import code that needs to be run by the client?

I need to use google map in my project, I use @googlemaps/extended-component-library library.@googlemaps/extended-component-library

import '@googlemaps/extended-component-library/api_loader.js';
import '@googlemaps/extended-component-library/split_layout.js';
import '@googlemaps/extended-component-library/place_overview.js';

export default function Gmap() {
    return (
        <>
            <gmpx-api-loader key="MY_KEY"></gmpx-api-loader>
                <gmpx-place-overview slot="fixed" place="ChIJ39Y-tdg1fYcRQcZcBb499do"></gmpx-place-overview>
                <gmp-map
                    center="37.4220656,-122.0840897"
                    zoom="10"
                    map-id="DEMO_MAP_ID"
                    style={{ height: "400px" }}
                ></gmp-map>

            <script
                src="https://maps.googleapis.com/maps/api/js?key=MY_KEY&callback=initMap&v=beta"
                defer
            ></script>
        </>
    );
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>

When I import it like this, next will report the error document is not definedenter image description here

Is there any way to import it only on the client side? I don't want to use @googlemaps/extended-component-library/react

Upvotes: 0

Views: 83

Answers (2)

Roshan Yadav
Roshan Yadav

Reputation: 1

This work for me , i am using next js 14.3 version .

"use client"

import {APILoader} from '@googlemaps/extended-component-library/react';
import React from 'react';
import './App.css';

function AddressTest() {
  const googleMapsApiKey = process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY || '';


  return (
    <div>
      <APILoader apiKey={googleMapsApiKey} solutionChannel="GMP_GCC_mapandmarker_v2" />
      <gmp-map map-id="4f33f0e7f6ab915e" center="-33.86882,151.20930" zoom="11">
        <gmp-advanced-marker position="-33.86882,151.20930" />
      </gmp-map>
    </div>
  );
}



export default AddressTest
gmp-map {
    width: 100%;
    height: 30em;
  }
  
 

Don't forget to import css , the map doesn't show you must have to put css.

Upvotes: 0

Parth Nariya
Parth Nariya

Reputation: 44

you can mark this page to client component by specifying "use client". refer : official docs here

"use client" in client component

Upvotes: -1

Related Questions