Skip to main content

Library

If you want more control over the map functionality with direct access to the map engine's methods you can embed a map in a "library" way. In this guide, we show how to do that on the example of the existing Progressive Web Application (PWA) application.

Create PWA app

Let's create the main application where we add our map.

npx create-react-app my-app --template cra-template-pwa

Embed map

Add pcmap.js and pcmap.css files on a page where you want to show the map. After that, the PCMap object will be available globally on your page. In our case, we add them to the public/index.html file into the head tag.

note

The https://pcmap-website-demo.netlify.app is a demo map. In your application, you should use links provided by the Point-Maps team.

public/index.html
<head>
<!-- other content -->
<link
href="https://pcmap-website-demo.netlify.app/lib/pcmap.css"
rel="stylesheet"
/>
<script src="https://pcmap-website-demo.netlify.app/lib/pcmap.js"></script>
</head>

Initialise map

In the example below you can see how the map is initialised in React app, but ultimately you only need to provide the map container div element to the PCMap.initApp function.

src/App.js
function App() {
const mapRef = React.useRef(null)

React.useEffect(() => {
if (!mapRef.current) {
return
}

PCMap.initApp(mapRef.current)
}, [])

return <div style={{ width: '100vw', height: '100vh' }} ref={mapRef}></div>
}

Offline mode

By default the PWA mode is disabled in our app, to enable it open the src/index.js and change:

src/index.js
//serviceWorkerRegistration.unregister();
serviceWorkerRegistration.register()

To make the map work in an offline mode we must cache the map files. The solution will vary depending on what toolset you are using in your project, but if your choice is Workbox then you should define how the requests to the map files must be treated. For that, you can use the registerRoute utility function. Below you can see an example of registering additional routes in our demo app:

src/service-worker.js
// ...
// Any other custom service worker logic can go here.

registerRoute(
new RegExp('.*(pcmap-website-demo.netlify.app|cdn.filestackcontent.com).*'),
new StaleWhileRevalidate({
cacheName: 'webmap',
}),
)

Interaction

The PCMap.initApp accepts the onReady callback which, once the map is ready, returns the map object for direct interaction with the map. The map engine exposes the Events and Methods you can leverage to fine-tune the map behaviour.

function App() {
const mapRef = React.useRef(null)

React.useEffect(() => {
if (!mapRef.current) {
return
}

PCMap.initApp(mapRef.current, {
onReady: ({ map }) => {
map.showDirections({ sourceId: '1', destinationId: '2' })
},
})
}, [])

return <div style={{ width: '100vw', height: '100vh' }} ref={mapRef}></div>
}