Geolocation | AIUI | Rokid

Use navigator.geolocation to get the current position or receive position updates. Both operations report latitude and longitude in the WGS-84 coordinate system. Use Geoc…

Geolocation

Use navigator.geolocation to get the current position or receive position updates. Both operations report latitude and longitude in the WGS-84 coordinate system. Use Geocoder to look up an address from supplied coordinates.

Look Up an Address from Coordinates

When you already have coordinates, use Geocoder without requesting the device's position:

const geocoder = new Geocoder({ level: 'city', acceptLanguages: ['en-US'] });
try {
  const address = await geocoder.getFromLocation(30.2741, 120.1551);
  console.log(address?.formattedAddress ?? 'No address found');
} catch (error) {
  console.error('Address lookup failed:', error.message);
}

Supply latitude and longitude in the WGS-84 coordinate system. This lookup does not require device location permission, but address lookup is not available in every environment. Returned fields can be null, so provide fallback text.

Get the Current Position

getCurrentPosition() requests one position. Read the coordinates and accuracy from position.coords after it succeeds:

navigator.geolocation.getCurrentPosition(
  (position) => {
    const { latitude, longitude, accuracy } = position.coords;
    console.log('Current position:', latitude, longitude);
    console.log('Accuracy:', accuracy, 'metres');
  },
  (error) => {
    console.error('Location failed:', error.message);
  },
  {
    enableHighAccuracy: true,
    timeout: 5000,
    maximumAge: 0,
  }
);

The reverseGeocode option for getCurrentPosition() is temporarily unavailable. Use Geocoder above to look up an address from the coordinates.

Watch Position Changes

watchPosition() returns a watch ID. Stop the watch with that ID when the page no longer needs updates:

const watchId = navigator.geolocation.watchPosition(
  (position) => {
    console.log(position.coords.latitude, position.coords.longitude);
  },
  (error) => {
    console.error(error.code, error.message);
  }
);

// Call this when location updates are no longer needed.
navigator.geolocation.clearWatch(watchId);

Stopping unused watches avoids unnecessary positioning work and battery use.

Declare Location Permission

Declare the GEOLOCATION permission in app.json before using location:

{
  "permissions": ["GEOLOCATION"]
}

The user must also allow the device's location permission. The error callback reports permission denial, an unavailable position, or a timeout.

API Reference

navigator.geolocation

Returns the application's Geolocation object. The runtime provides this object; applications do not construct it.

getCurrentPosition(success, error?, options?)

Requests one current position. The method has no return value. The success callback receives a GeolocationPosition with WGS-84 latitude and longitude. The reverseGeocode option is temporarily unavailable. Use Geocoder to look up the returned coordinates.

ParameterTypeRequiredDescription
success(position) => voidYesCalled when a position is available.
error(error) => voidNoCalled when positioning fails.
optionsPositionOptionsNoAccuracy, timeout, and cache settings.

watchPosition(success, error?, options?)

Watches for position changes and returns a numeric watchId. Each successful update delivers a GeolocationPosition with WGS-84 latitude and longitude to the success callback. Pass the watchId to clearWatch() when updates are no longer needed.

clearWatch(watchId)

Stops the location watch identified by watchId.

PositionOptions

FieldTypeDescription
enableHighAccuracybooleanPrefer a more accurate position. Defaults to false; high-accuracy positioning may use more power.
timeoutnumberMaximum time to wait, in milliseconds; the device decides when omitted.
maximumAgenumberMaximum acceptable age of a cached position, in milliseconds; the device decides when omitted.
reverseGeocodeobjectSet enabled: true to look up an address. This option is temporarily unavailable for getCurrentPosition(); use Geocoder for coordinate lookup. level is country, region, city, district, or street (default city); acceptLanguages is an ordered array of language tags.

GeolocationPosition

coords.latitude and coords.longitude are expressed in decimal degrees.

PropertyTypeDescription
coords.latitudenumberLatitude.
coords.longitudenumberLongitude.
coords.accuracynumberCoordinate accuracy in metres.
coords.altitudenumber | nullAltitude, or null when unavailable.
coords.altitudeAccuracynumber | nullAltitude accuracy, or null when unavailable.
coords.headingnumber | nullDirection of travel, or null when unavailable.
coords.speednumber | nullTravel speed, or null when unavailable.
timestampnumberTimestamp when the position was obtained.
addressGeocodeAddress | nullThe address, or null when not requested, unavailable, or not found.
reverseGeocodeStatusstringAddress status: not-requested, success, not-found, unavailable, timeout, error, or rate-limited.

GeolocationPositionError

codeConstantDescription
1PERMISSION_DENIEDThe user or application did not allow location access.
2POSITION_UNAVAILABLEA position is currently unavailable.
3TIMEOUTNo position was available before the timeout.

message contains a human-readable description of the error.

Geocoder

new Geocoder(options?)

Creates a reusable address lookup. options.level and acceptLanguages have the same meaning as in the position options above; timeout is the lookup timeout in milliseconds, defaulting to 3000, with a range of 0 to 2147483647.

getFromLocation(latitude, longitude)

Looks up one WGS-84 coordinate and returns Promise<GeocodeAddress | null>. Latitude must be between -90 and 90 and longitude between -180 and 180. A missing match returns null; an unavailable service, timeout, or lookup failure rejects with error code UNAVAILABLE, TIMEOUT, or PROVIDER_ERROR, respectively.

GeocodeAddress

formattedAddress, country, countryCode, region, city, district, street, streetNumber, and postalCode are each a string or null. The actual fields depend on the address service.

Coordinate Systems and Conversion

The same location can have different latitude and longitude values in different coordinate systems. Before plotting a position, check which coordinate system the target map API accepts. A mismatch shifts the marker on the map.

Coordinate systemBackgroundCommon uses
WGS-84The World Geodetic System 1984 is the global geodetic reference system used by GPS.GPS module output, AIUI position results, and KML data for Google Earth. NGA WGS-84 overview, Google KML documentation
GCJ-02Developed by China's former State Bureau of Surveying and Mapping, GCJ-02 is also known as the Mars coordinate system. It applies a location-dependent offset to WGS-84 coordinates.Map markers, place search, and route planning in Amap and Tencent Maps in mainland China. Amap coordinate systems, Tencent coordinate systems
BD-09Baidu applies a second offset to GCJ-02. BD09LL is the latitude and longitude variant. BD09MC uses projected Mercator coordinates in metres.Map markers and place services in Baidu Maps in mainland China typically use BD09LL. Baidu coordinate systems

Check the input coordinate system for the API, region, and map layer you use. The Google Maps JavaScript API uses WGS-84 for latitude and longitude. The Baidu Maps JS API also uses WGS-84 for maps outside China. Google Maps coordinates, Baidu Maps JS API coordinate systems

Convert with a Map Provider

Store the original WGS-84 position from position.coords. Convert it once when plotting a marker or calling a map service that expects a different coordinate system. Pass the original position directly to Geocoder.getFromLocation(latitude, longitude).

ConversionHow to convert
WGS-84 → GCJ-02Use coordsys=gps with Amap or type=1 with Tencent. Amap coordinate conversion, Tencent coordinate conversion
WGS-84 → BD09LLUse model=2 with Baidu. Baidu coordinate conversion
GCJ-02 → BD09LLUse model=1 with Baidu. Baidu coordinate conversion
BD09LL → GCJ-02Use coordsys=baidu with Amap, type=3 with Tencent, or model=5 with Baidu. Amap coordinate conversion, Tencent coordinate conversion, Baidu coordinate conversion
BD09LL ↔ BD09MCUse Baidu's model=3 for coordinates in metres or model=4 for latitude and longitude. Baidu coordinate conversion

For latitude and longitude inputs, Amap's locations and Baidu's coords use longitude,latitude. Tencent's locations uses latitude,longitude. For example, send the same WGS-84 point as locations=120.1551,30.2741 to Amap and locations=30.2741,120.1551 to Tencent.

Convert Back to WGS-84

The map conversion APIs above do not convert back to WGS-84. Use the stored WGS-84 coordinates when you need the original position. If your source provides only GCJ-02 or BD09LL, a third-party library such as gcoord can approximate the inverse transformation. Check the result against your application's accuracy requirements.

In a Node.js project with gcoord installed, pass [longitude, latitude], the source coordinate system, and the target coordinate system. This example converts GCJ-02 to WGS-84. For Baidu latitude and longitude, use gcoord.BD09LL as the source.

import gcoord from 'gcoord';

const gcj02 = [120.1598, 30.2717];
const [longitude, latitude] = gcoord.transform(gcj02, gcoord.GCJ02, gcoord.WGS84);
console.log({ longitude, latitude });