hamuga-imap-sdk-react-native
v2.1.1
Published
Hamuga iMap SDK for React Native
Maintainers
Readme
Hamuga iMap SDK for React Native
English
hamuga-imap-sdk-react-native provides a Hamuga map component for React Native with built-in suggestions, POI search, routing helpers, location controls, and API-key authenticated Hamuga tiles.
- Package:
hamuga-imap-sdk-react-native - Current version:
2.1.1 - Node.js:
>=18 - Primary platforms: iOS and Android
- Map engine:
@maplibre/maplibre-react-native ^11.3.7 - Default gateway:
https://gateway.hamuga.mn - Default style:
https://cdn.hamuga.mn/style.json
Install
npm install hamuga-imap-sdk-react-native react-native-safe-area-context
# or
yarn add hamuga-imap-sdk-react-native react-native-safe-area-contextInstall native dependencies after adding the package:
cd ios
pod installThe package requires a React Native app with native iOS/Android build support. Follow the MapLibre React Native setup documentation for platform-specific prerequisites.
Quick start
You can pass the API key directly to HamugaMap:
import React, { useRef } from 'react';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import {
HamugaMap,
type HamugaMapRef,
} from 'hamuga-imap-sdk-react-native';
const apiKey = 'your_hamuga_api_key'; // Load this from your app configuration.
export default function App() {
const mapRef = useRef<HamugaMapRef>(null);
return (
<SafeAreaProvider>
<HamugaMap
ref={mapRef}
apiKey={apiKey}
search
showZoomControls
showCompassControl
showMyLocationButton
showScaleBar
center={[106.9163376, 47.919118]}
zoom={14.5}
/>
</SafeAreaProvider>
);
}For a shared key/configuration, initialize HamugaApi once and omit the component apiKey:
import { HamugaApi } from 'hamuga-imap-sdk-react-native';
HamugaApi.initialize({
apiKey: 'your_hamuga_api_key',
baseUrl: 'https://gateway.hamuga.mn',
});Do not ship server credentials in a mobile bundle. Use a client-safe key with the restrictions intended for the application.
Coordinates
React Native coordinates use [longitude, latitude]:
const ulaanbaatar: [number, number] = [106.9163376, 47.919118];This differs from Flutter's LatLng, whose constructor names are latitude and longitude.
Search and POI
The component renders its own search UI when search is enabled. Use the ref for imperative requests:
const suggestion = await mapRef.current?.getSuggest('Sukhbaatar Square');
const pois = await mapRef.current?.getPoi({
query: 'restaurant',
page: 1,
size: 10,
});Use searchWithinViewport when the query should be constrained to the visible map bounds. POI results contain a normalized title, optional subtitle, optional [longitude, latitude] coordinate, and the original raw response item.
Standalone API client
Use the client without rendering a map:
import { createHamugaSearchClient } from 'hamuga-imap-sdk-react-native';
const client = createHamugaSearchClient({
apiKey: 'your_hamuga_api_key',
});
const suggestions = await client.getSuggest('central');
const results = await client.getPoi({ query: 'hospital' });
const transit = await client.planRoute({
from: [106.9, 47.9],
to: [106.91, 47.92],
mode: 'WALK',
});
const route = await client.calculateRoute({
locations: [
{ lat: 47.918, lon: 106.9176 },
{ lat: 47.92, lon: 106.92 },
],
costing: 'pedestrian',
});The gateway methods are:
suggest(query)/getSuggest(query)→/engine/suggestsearchPois(options)/getPoi(options)→/engine/poiplanRoute(options)→/route/routers/default/plancalculateRoute(options)→/route/other/v1/route
All authenticated requests use the x-api-key header. Non-successful responses reject with an error; handle calls with try/catch.
HamugaMap options
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| apiKey | string? | Global HamugaApi key | Key used for map and search requests. |
| center | [number, number] | [106.9163376, 47.919118] | Initial [longitude, latitude]. |
| zoom | number | 14.5 | Initial zoom level. |
| mapStyle | string \| object | https://cdn.hamuga.mn/style.json | Remote style URL or style object. |
| search | boolean | false | Render the built-in search UI. |
| searchWithinViewport | boolean | false | Add visible-map bounds to POI searches. |
| searchPlaceholder | string | Байршил хайх... | Search input placeholder. |
| gatewayBaseUrl | string | https://gateway.hamuga.mn | Search, POI, and routing gateway override. |
| tileUrlTemplate | string | ${gatewayBaseUrl}/tile/tiles/{z}/{x}/{y}.pbf | Tile-only URL template override. |
| uiTheme | object | Default Hamuga theme | Override overlay colors, radii, maximum width, and blur. |
| onCameraTrackingChanged | (isTracking: boolean) => void | undefined | Called when user-location camera tracking changes. |
| showZoomControls | boolean | false | Render zoom controls. |
| showCompassControl | boolean | false | Render compass control. |
| showMyLocationButton | boolean | true | Render the location button. |
| showScaleBar | boolean | false | Render the scale bar. |
| enableHapticFeedback | boolean | false | Enable haptic feedback for supported controls. |
| mapPadding | object | {} | Insets for the map and overlay controls. |
HamugaMapRef methods
| Method | Purpose |
| --- | --- |
| suggest(query) / getSuggest(query) | Request a typeahead suggestion. |
| searchPois(options) / getPoi(options) | Search normalized POI suggestions. |
| planRoute(options) | Request an OTP-style route plan. |
| calculateRoute(options) | Request a Valhalla-style route calculation. |
Custom styles and tiles
The default style is loaded from https://cdn.hamuga.mn/style.json. The SDK patches sources.hamuga.tiles to tileUrlTemplate and adds x-api-key only to matching tile requests. gatewayBaseUrl remains the base URL for search, POI, and routing. It does not send the key to third-party style, glyph, or sprite URLs. A custom style should preserve a hamuga source when it expects this automatic tile patching. If the style uses another source layout, provide and authenticate that style yourself.
Troubleshooting
- Map does not render: confirm an API key is available, the native MapLibre setup is complete, and the style URL is reachable.
- Search throws
Search client not initialized: passapiKeyor callHamugaApi.initialize(...)before using the ref. - Tiles fail: verify
tileUrlTemplate, API-key permissions, network access, and the native MapLibre logs. - iOS build fails after install: run
cd ios && pod installand rebuild the app. - Layout is incorrect: make the map parent fill the available space (
flex: 1) and wrap the app inSafeAreaProviderwhen using the SDK overlays.
Example app
cd example
yarn install
yarn start
# In another terminal:
yarn ios
# or
yarn androidCreate example/.env from example/.env.example:
HAMUGA_API_KEY=your_api_key_hereThe example reads the key through react-native-dotenv; never commit a real key.
Development checks
yarn typecheck
yarn lint
yarn testLicense
Apache-2.0.
Монгол хэлээр
hamuga-imap-sdk-react-native нь React Native-д зориулсан Hamuga map component юм. Built-in suggestion, POI хайлт, routing helper, location control болон API key бүхий Hamuga tile authentication-ийг өгнө.
- Одоогийн хувилбар:
2.1.1 - Node.js:
>=18 - Үндсэн platform: iOS, Android
- Map engine:
@maplibre/maplibre-react-native ^11.3.7 - Үндсэн gateway:
https://gateway.hamuga.mn - Үндсэн style:
https://cdn.hamuga.mn/style.json
Суулгах
npm install hamuga-imap-sdk-react-native react-native-safe-area-context
# эсвэл
yarn add hamuga-imap-sdk-react-native react-native-safe-area-contextNative dependency суулгасны дараа iOS pod-ийг ажиллуул:
cd ios
pod installPackage нь native iOS/Android build support-той React Native app шаарддаг. Platform prerequisite-ийг MapLibre React Native setup-ээс дага.
Богино жишээ
API key-г HamugaMap component-д шууд өгч болно:
import React, { useRef } from 'react';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import {
HamugaMap,
type HamugaMapRef,
} from 'hamuga-imap-sdk-react-native';
const apiKey = 'your_hamuga_api_key';
export default function App() {
const mapRef = useRef<HamugaMapRef>(null);
return (
<SafeAreaProvider>
<HamugaMap
ref={mapRef}
apiKey={apiKey}
search
showZoomControls
showCompassControl
showMyLocationButton
showScaleBar
center={[106.9163376, 47.919118]}
zoom={14.5}
/>
</SafeAreaProvider>
);
}Нэг shared key/configuration ашиглах бол HamugaApi-г нэг удаа initialize хийгээд component-ийн apiKey-г орхиж болно:
import { HamugaApi } from 'hamuga-imap-sdk-react-native';
HamugaApi.initialize({
apiKey: 'your_hamuga_api_key',
baseUrl: 'https://gateway.hamuga.mn',
});Mobile bundle-д server credential бүү оруул. Аппад зориулсан client-safe key ашигла.
Координат
React Native координат нь [longitude, latitude] дараалалтай:
const ulaanbaatar: [number, number] = [106.9163376, 47.919118];Flutter-ийн LatLng constructor нь latitude болон longitude талбарын нэр ашигладаг.
Search болон POI
search асаахад component өөрийн search UI-г зурна. Ref ашиглан imperative request хий:
const suggestion = await mapRef.current?.getSuggest('Сүхбаатарын талбай');
const pois = await mapRef.current?.getPoi({
query: 'restaurant',
page: 1,
size: 10,
});Query-г харагдаж буй map bounds-аар хязгаарлах бол searchWithinViewport ашигла. POI result нь normalized title, optional subtitle, optional [longitude, latitude] coordinate, мөн эх raw item-ийг агуулна.
Map-гүй API client
Map render хийхгүйгээр client ашиглаж болно:
import { createHamugaSearchClient } from 'hamuga-imap-sdk-react-native';
const client = createHamugaSearchClient({
apiKey: 'your_hamuga_api_key',
});
const suggestions = await client.getSuggest('central');
const results = await client.getPoi({ query: 'hospital' });
const transit = await client.planRoute({
from: [106.9, 47.9],
to: [106.91, 47.92],
mode: 'WALK',
});
const route = await client.calculateRoute({
locations: [
{ lat: 47.918, lon: 106.9176 },
{ lat: 47.92, lon: 106.92 },
],
costing: 'pedestrian',
});Gateway method-ууд:
suggest(query)/getSuggest(query)→/engine/suggestsearchPois(options)/getPoi(options)→/engine/poiplanRoute(options)→/route/routers/default/plancalculateRoute(options)→/route/other/v1/route
Authenticated request бүр x-api-key header ашиглана. Амжилтгүй response error болж reject хийнэ. Async дуудлагыг try/catch-ээр барь.
HamugaMap options
| Option | Type | Default | Тайлбар |
| --- | --- | --- | --- |
| apiKey | string? | Global HamugaApi key | Map болон search request-ийн key. |
| center | [number, number] | [106.9163376, 47.919118] | Эхний [longitude, latitude]. |
| zoom | number | 14.5 | Эхний zoom level. |
| mapStyle | string \| object | https://cdn.hamuga.mn/style.json | Remote style URL эсвэл style object. |
| search | boolean | false | Built-in search UI зурна. |
| searchWithinViewport | boolean | false | POI query-д харагдаж буй map bounds нэмнэ. |
| searchPlaceholder | string | Байршил хайх... | Search input-ийн placeholder. |
| gatewayBaseUrl | string | https://gateway.hamuga.mn | Search, POI болон routing gateway override. |
| tileUrlTemplate | string | ${gatewayBaseUrl}/tile/tiles/{z}/{x}/{y}.pbf | Зөвхөн tile URL template override. |
| uiTheme | object | Default Hamuga theme | Overlay-ийн өнгө, radius, maximum width, blur-ийг override хийнэ. |
| showZoomControls | boolean | false | Zoom control зурна. |
| showCompassControl | boolean | false | Compass control зурна. |
| showMyLocationButton | boolean | true | Location button зурна. |
| showScaleBar | boolean | false | Scale bar зурна. |
| enableHapticFeedback | boolean | false | Дэмждэг control-д haptic feedback асаана. |
| onCameraTrackingChanged | (isTracking: boolean) => void | undefined | User-location camera tracking өөрчлөгдөхөд дуудна. |
| mapPadding | object | {} | Map болон overlay control-ийн inset. |
HamugaMapRef method
| Method | Үүрэг |
| --- | --- |
| suggest(query) / getSuggest(query) | Typeahead suggestion хүснэ. |
| searchPois(options) / getPoi(options) | Normalized POI suggestion хайна. |
| planRoute(options) | OTP-style route plan хүснэ. |
| calculateRoute(options) | Valhalla-style route calculation хүснэ. |
Custom style ба tile
Default style нь https://cdn.hamuga.mn/style.json-оос ачаалагдана. SDK нь sources.hamuga.tiles-ийг tileUrlTemplate болгож patch хийнэ. gatewayBaseUrl нь search, POI болон routing-ийн base URL хэвээр байна. x-api-key-г зөвхөн тохирсон tile request-д нэмээд third-party style, glyph, sprite URL рүү илгээхгүй. Automatic tile patching ашиглах custom style-д hamuga source-ийг хадгал. Өөр source layout ашиглавал style болон authentication-ийг өөрөө тохируул.
Түгээмэл алдаа
- Map харагдахгүй: API key байгаа, native MapLibre setup дууссан, style URL хүрэх боломжтой эсэхийг шалга.
Search client not initialized:apiKeyөгч эсвэл ref ашиглахаас өмнөHamugaApi.initialize(...)дууд.- Tile алдаа:
gatewayBaseUrl, API-key permission, network access болон native MapLibre log-ийг шалга. - iOS build алдаа: суулгасны дараа
cd ios && pod installажиллуулаад app-аа дахин build хий. - Layout буруу: Map-ийн parent available space-ийг
flex: 1-ээр дүүргэж, SDK overlay ашиглавалSafeAreaProvider-оор wrap хий.
Жишээ апп
cd example
yarn install
yarn start
# Өөр terminal-д:
yarn ios
# эсвэл:
yarn androidexample/.env.example-ийг хуулж example/.env үүсгэ:
HAMUGA_API_KEY=your_api_key_hereExample нь react-native-dotenv-оор key-г уншина. Бодит key-г commit бүү хий.
Хөгжүүлэлтийн шалгалт
yarn typecheck
yarn lint
yarn testLicense
Apache-2.0.
