Working with React

Ahoy Maps library for your react projects

Setup / Installation

There’s two ways to use Ahoy maps sdk for your project , either through

  1. Inline script
  2. .npmrc

Inline Script

The easiest way to use ahoy maps sdk is to use the script hosted on cdn .

Add this script tag in the <head></head> tag of index.html

<script
  type="module"
  src="https://ahoymapsfrontend.blob.core.windows.net/ahoy-storage/ahoy-ahoy-maps-sdk.mjs"
  defer
></script>

.npmrc

To use the package through npm , create a project by following these steps

The recommended way to use ahoy-maps-sdk for Angular within this environment is to install ahoy-maps-sdk NPM package which is hosted at https://pkgs.dev.azure.com/.

Add a registry entry to the NPM configuration by creating a .npmrc file in the root directory with the following content.

registry=https:https://registry.npmjs.org/
registry=https://pkgs.dev.azure.com/ahoyapp/Frontend/_packaging/ahoy-frontend-feed-emerald/npm/registry/
always-auth=true

; begin auth token
//pkgs.dev.azure.com/ahoyapp/Frontend/_packaging/ahoy-frontend-feed-emerald/npm/registry/:username=ahoyapp
//pkgs.dev.azure.com/ahoyapp/Frontend/_packaging/ahoy-frontend-feed-emerald/npm/registry/:_password=N21wb3hkeml3YnNtYWRxZGJlYXpmdGVmYXR6eHZvZ2lmNXluYXdjZjd5dXNrd2xweWt1cQ==
//pkgs.dev.azure.com/ahoyapp/Frontend/_packaging/ahoy-frontend-feed-emerald/npm/registry/:email=[YOUR_EMAIL]
//pkgs.dev.azure.com/ahoyapp/Frontend/_packaging/ahoy-frontend-feed-emerald/npm/:username=ahoyapp
//pkgs.dev.azure.com/ahoyapp/Frontend/_packaging/ahoy-frontend-feed-emerald/npm/:_password=N21wb3hkeml3YnNtYWRxZGJlYXpmdGVmYXR6eHZvZ2lmNXluYXdjZjd5dXNrd2xweWt1cQ==
//pkgs.dev.azure.com/ahoyapp/Frontend/_packaging/ahoy-frontend-feed-emerald/npm/:email=[YOUR_EMAIL]
; end auth token

add your email in the .npmrc , npm requires email to be set but doesn’t use the value

//pkgs.dev.azure.com/ahoyapp/Frontend/_packaging/ahoy-frontend-feed-emerald/npm/registry/:email=feax..@..com
//pkgs.dev.azure.com/ahoyapp/Frontend/_packaging/ahoy-frontend-feed-emerald/npm/:email=feax..@..com

After that the package from the @ahoy namespace can be installed as usual:

npm install --save @ahoy/ahoy-maps-sdk

Class Documentation

you can find the docs here

Get Started

Signup for Ahoy Movement Studio and obtain a Subscription Key, you can do so by signing up here

To load the map styles add the following to the head in index.html

<link
  rel="stylesheet"
  type="text/css"
  href="https://ahoymapsfrontend.blob.core.windows.net/ahoy-storage/styles.css"
/>

Add a div referencing it with useRef

<div ref={mapRef} class="map" style={{ height: "500px", width: "100%" }} />

In your component , add this line

const mapRef = React.useRef(null);

Webpack

when we use create-react-app command to generate a react application , Webpack 5 by default renames the “global” variable which is necessary for @ahoy/ahoy-maps-sdk

so add the react-app-rewired dependency to your project, and then add to your root folder a config-overrides.js file with the following contents:

module.exports = function override(config, env) {
    config.node = { global: false }
    return config
}

Finally, change the start script in package.json to use react-app-rewired, the scripts object should look like this:

"scripts": {
    "start": "react-app-rewired start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  }

Usage

import AhoyMapView class

  • if installed through npm

    import { AhoyMapView } from "@ahoy/ahoy-maps-sdk";
    
  • if using through inline script

    declare var AhoyMapView: any;
    

declare map state

const [map, setMap] = useState(null);

Initialize a Platform object with the key you received on the Ahoy Movement Studio . The call to the Platform method returns a promise , so make the method async . Check the complete code below for reference.

let platform = await AhoyMapView.service().Platform(SUBSCRIPTION_KEY);

Create a map instance by passing DefaultLayer and the mapRef

const defaultLayers = platform.createDefaultLayers();

const ahoyMap = AhoyMapView.Map(
  mapRef.current,
  defaultLayers.vector.normal.map,
  {
    zoom: 4,
    center: {
      lat: 34,
      lng: 41,
    },
  }
);

Add default interactions for zooming and panning on the map

const mapEvents = AhoyMapView.mapevents().MapEvents(ahoyMap);

const behavior = AhoyMapView.mapevents().Behavior(mapEvents);

Create Default buttons in ui to zoom and change map schemes

const ui = AhoyMapView.ui().UI.createDefault(map, defaultLayers);

when app runs in strict mode , the component renders twice.

This happens is an intentional feature of the React.StrictMode. It only happens in development mode and should help to find accidental side effects in the render phase.

But it will cause AhoyMaps to render twice so we can either

  1. Go to index.js and comment strict mode tag. You will find a single render.

    const root = ReactDOM.createRoot(document.getElementById("root"));
    
    root.render(
      //<React.StrictMode>
    
      <App />
    
      //</React.StrictMode>
    );
    
  2. or use this custom useEffectOnce hook

    export const useEffectOnce = (effect) => {
      const destroyFunc = useRef();
      const calledOnce = useRef(false);
      const renderAfterCalled = useRef(false);
    
      if (calledOnce.current) {
        renderAfterCalled.current = true;
      }
    
      useEffect(() => {
        if (calledOnce.current) {
          return;
        }
    
        calledOnce.current = true;
        destroyFunc.current = effect();
    
        return () => {
          if (!renderAfterCalled.current) {
            return;
          }
    
          if (destroyFunc.current) {
            destroyFunc.current();
          }
        };
      }, []);
    };
    

Complete code

Available Features

Move map focus to a desired coordinate

pass the coordinate and map instance to moveCamera Method readmore..

AhoyMapView.map().moveCamera({ lat: 47.15984, lng: 6.240234 }, map);

Resize map to the size of viewport

pass the map instance to the resize method readmore..

map.getViewPort(map).resize();

Set Zoom level of the map

pass the zoom level between 1-22 to the method readmore..

AhoyMapView.map().setZoomLevel(3, map);

Get center coordinates on the map

map.getCenter();

Show and hide traffic conditions on the map

//show

AhoyMapView.map().showTrafficConditions(defaultLayers, map);

//hide

AhoyMapView.map().hideTrafficConditions(defaultLayers, map);

Show and hide traffic incidents on the map

//show

AhoyMapView.map().showTrafficIncidents(defaultLayers, map);

//hide

AhoyMapView.map().hideTrafficIncidents(defaultLayers, map);

Add Marker on the Map

call createMarker method and add the markerObject returned to the map readmore..)

const marker = AhoyMapView.map().createMarker({
  lat: 34.161818,
  lng: 453.691406,
});

map.addObject(marker);

Add Polyline on the Map

call createPolyline method and add the markerObject returned to the map readmore..

const latLngArr = [
  53.3477, -6.2597, 100, 51.5008, -0.1224, 100, 48.8567, 2.3508, 100,

  52.5166, 13.3833, 100,
];

const polyline1 = AhoyMapView.map().createPolyline(2, "pink", latLngArr);

map.addObject(polyline1);

Add Polygon on the Map

call [createPolygon]) method and add the markerObject returned to the map readmore..

const latLngArr = [
  53.3477, -6.2597, 100, 51.5008, -0.1224, 100, 48.8567, 2.3508, 100,

  52.5166, 13.3833, 100, 52.5234, 13.39, 100,
];

const marker = AhoyMapView.map().createPolygon(latLngArr);

map.addObject(marker);

Remove marker/polygon/polyline from the map

call removeObject method on the map and pass the object you want to remove

map.removeObject(marker);