Skip to content

Instantly share code, notes, and snippets.

@wooogi123
Last active September 28, 2021 01:57
Show Gist options
  • Save wooogi123/902eb41bcee3c0bf0a991c297650482c to your computer and use it in GitHub Desktop.
Save wooogi123/902eb41bcee3c0bf0a991c297650482c to your computer and use it in GitHub Desktop.
import * as React from 'react';
import Head from 'next/head';
import Script from 'next/script';
export class NaverMapService {
private isInitialized: boolean;
constructor() {
this.isInitialized = false;
}
onScriptLoaded() {
this.isInitialized = true;
}
getServiceNamespace() {
if (!this.isInitialized) {
throw new Error('Naver map service not initialized');
}
return window.naver.maps;
}
}
const CLIENT_ID: string = 'CLIENT_ID';
const NaverMapContext = React.createContext<NaverMapService | null>(null);
const NScript = ({ children }: { children: React.ReactNode; }) => {
const [instance] = React.useState<NaverMapService>(new NaverMapService());
return (
<NaverMapContext.Provider value={instance}>
<Head>
<Script
src={`https://openapi.map.naver.com/openapi/v3/maps.js?ncpClientId=${CLIENT_ID}`}
onLoad={() => {
instance.onScriptLoaded();
}}
/>
</Head>
{children}
</NaverMapContext.Provider>
);
}
export const useNaverMapService = () => {
const instance = React.useContext(NaverMapContext);
if (instance === null) throw new Error();
return instance;
}
// Usage Example
// pages/map.tsx
const DisplayMap: React.FC = () => {
const naverMapInstance = useNaverMapService();
const ref = React.useRef<HTMLDivElement | null>(null);
const mapInstance = React.useRef<NaverMap /* navermap Map 타입 */ | null>(null);
React.useEffect(() => {
const el = ref.current;
if (el === null) return;
if (mapInstance.current !== null) return;
mapInstance.current = naverMapInstance.Map(el, { zoom: 10, });
}, []);
return (
<div ref={ref}></div>
);
};
const Map: React.FC = () => {
<NScript>
<DisplayMap />
</NScript>
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment