Skip to main content

Web SDK

This is the documentation for the Radar Web SDK.

The source can be found on GitHub here. Or, see the radar-sdk-js package on npm here.

Install#

In an HTML page, add the SDK script and stylesheet:

<link href="https://js.radar.com/v4.1.11/radar.css" rel="stylesheet"><script src="https://js.radar.com/v4.1.11/radar.min.js"></script>

In a web app, install the package from npm:

npm install --save radar-sdk-js maplibre-gl

The SDK has a dependency on maplibre-gl.

Then, import the library and stylesheet:

import Radar from 'radar-sdk-js';import 'radar-sdk-js/dist/radar.css';

Setup#

Initialize#

Initialize the library with your publishable API key, found on the Settings page:

Radar.initialize('prj_live_pk_...');

Optionally, you can specify configuration options:

The initialize call takes an optional second argument that is an object with additional configuration options.

Radar.initialize('prj_live_pk_...', {  /* custom options here */});

Available options include:

NameDefaultPossible valuesDescription
logLevelerrornone, info, warn, errorDetermines the log level for console logging. Defaults to error when using a test publishable key.
cacheLocationMinutesnullnumberDetermines whether to reuse previous location updates. A cache ttl in minutes. If null or 0, will always request a new location.
locationMaximumAgenullnumberDetermines whether to use old browser locations. A maximum age in milliseconds. If null or 0, will always request a new location. See getCurrentPosition options().
locationTimeout30000numberThe number of milliseconds to wait for a location update before an error is thrown. Defaults to 30 seconds.
desiredAccuracyhighhigh, medium, lowDetermines the desired accuracy of location updates. Note that higher accuracy can result in slower response times.

Geofencing#

Identify user#

To identify the user when logged in, call:

Radar.setUserId(userId);

where userId is a stable unique ID for the user.

To set an optional dictionary of custom metadata for the user, call:

Radar.setMetadata(metadata);

where metadata is a JSON object with up to 16 keys and values of type string, boolean, or number.

Finally, to set an optional description for the user, displayed in the dashboard, call:

Radar.setDescription(description);

where description is a string.

You only need to call these functions once, as these settings will be persisted across browser sessions in cookies.

Foreground tracking#

Once you have initialized the SDK and the user has granted permissions, you can track the user's location.

The SDK uses the HTML5 geolocation API to determine the user's location.

To track the user's location, call:

Radar.trackOnce()  .then((result) => {    const { location, user, events } = result;    // do something with location, user, or events  })  .catch((err) => {    // handle error  });

If the request fails, err will be one of:

  • RadarPublishableKeyError: SDK not initialized
  • RadarLocationPermissionsError: location permissions not granted
  • RadarLocationError: location services error or timeout (10 seconds)
  • RadarTimeoutError: network timeout (10 seconds)
  • RadarBadRequestError: bad request (missing or invalid params)
  • RadarUnknownError: unauthorized (invalid API key)
  • RadarPaymentRequiredError: payment required (organization disabled or usage exceeded)
  • RadarForbiddenError: forbidden (insufficient permissions or no beta access)
  • RadarNotFoundError: not found
  • RadarRateLimitError: too many requests (rate limit exceeded)
  • RadarServerError: internal server error
  • RadarUnknownError: unknown error

If the error is the result of a failed API call, err will include an HTTP response code and the API response body:

err.code; // HTTP response codeerr.response; // API response body

Manual tracking#

Alternatively, you can manually update the user's location with any location by calling:

Radar.trackOnce({  latitude: 39.2904,  longitude: -76.6122,  accuracy: 65}).then((result) => {  const { location, user, events } = result;  // do something with location, user, or events}).catch((err) => {  // handle error});

Get location#

You can also get a single location update without sending it to the server:

Radar.getLocation()  .then((result) => {    const { location } = result;    // do something with location  })  .catch((err) => {    // handle error  });

Context#

With the context API, get context for a location without sending device or user identifiers to the server:

Radar.getContext()  .then((result) => {    const { location, geofences, place, country, state, dma, postalCode } = result;    // do something with results  })  .catch((err) => {    // handle error  });

Maps#

Geocoding#

With the forward geocoding API, geocode an address, converting address to coordinates:

Radar.forwardGeocode({ query: '841 broadway, new york, ny' })  .then((result) => {    const { addresses } = result;    // do something with addresses  })  .catch((err) => {    // handle error  });

With the reverse geocoding API, reverse geocode a location, converting coordinates to address:

Radar.reverseGeocode({ latitude: 40.783826, longitude: -73.975363 })  .then((result) => {    const { addresses } = result;    // do something with addresses  })  .catch((err) => {    // handle error  });

With the IP geocoding API, geocode the device's current IP address, converting IP address to city, state, and country:

Radar.ipGeocode()  .then((result) => {    const { ip, address, proxy } = result;    // do something with results  })  .catch((err) => {    // handle error  });

Search#

With the autocomplete API, autocomplete partial addresses and place names, sorted by relevance:

Radar.autocomplete({  query: '841 bro',  near: {    latitude: 40.783826,    longitude: -73.975363  },  limit: 10}).then((result) => {  const { addresses } = result;  // do something with addresses}).catch((err) => {  // handle error});

With the geofence search API, search for geofences near a location, sorted by distance:

Radar.searchGeofences({  radius: 1000,  tags: ['venue'],  limit: 10}).then((result) => {  const { geofences } = result;  // do something with geofences}).catch((err) => {  // handle error});

With the places search API, search for places near a location, sorted by distance:

Radar.searchPlaces({  near: {    latitude: 40.783826,    longitude: -73.975363  },  radius: 1000,  chains: ['starbucks'],  limit: 10}).then((result) => {  const { places } = result;  // do something with places}).catch((err) => {  // handle error});

With the address validation API, validate a structured address in the US or Canada:

Radar.validateAddress({  addressLabel: '841 BROADWAY',  city: 'NEW YORK',  stateCode: 'NY',  postalCode: '10003',  countryCode: 'US',}).then((response) => {  const { address, result } = response;  // do something with validated address result}).catch((err) => {  // handle error});

Distance#

With the distance API, calculate the travel distance and duration between two locations:

Radar.distance({  origin: {    latitude: 40.78382,    longitude: -73.97536  },  destination: {    latitude: 40.70390,    longitude: -73.98670  },  modes: [    'foot',    'car'  ],  units: 'imperial'}).then((result) => {  const { routes } = result;  const { geodesic, foot, bike, car } = routes;  // do something with distance result}).catch((err) => {  // handle error});

Matrix#

With the matrix API, calculate the travel distances and durations between multiple origins and destinations for up to 25 routes:

Radar.matrix({  origins: [{    latitude: 40.70390,    longitude: -73.98690  }],  destinations: [{    latitude: 40.70390,    longitude: -73.98690  },  {    latitude: 40.73237,    longitude: -73.94884  }],  modes: 'car',  units: 'imperial'}).then((result) => {  const { origins, destinations, matrix } = result;  matrix.forEach((matrixResult) => {    const { distance, duration, originIndex, destinationIndex } = matrixResult;    // do something with matrix result  });}).catch((err) => {  // handle error});

Maps and UI kits#

The React Native SDK also has UI components for maps and address autocomplete. Learn more in the Maps Platform documentation.

Support#

Have questions? We're here to help! Email us at support@radar.com.