@smarthivelabs-devs/geocore-react
v2.4.0
Published
Geocore React SDK — hooks and components for React 18+ (geo, weather, pricing, countries)
Readme
@smarthivelabs-devs/geocore-react
React hooks and components for the Geocore SDK. Wraps all 14 geo-operations, weather, and the SmartHive Pricing Engine in ergonomic hooks with built-in loading and error state.
Installation
npm install @smarthivelabs-devs/geocore-react
# peer deps
npm install react react-domSetup
Wrap your app with GeocoreProvider:
import { GeocoreProvider } from '@smarthivelabs-devs/geocore-react';
// Backend mode (recommended — API keys stay on your server)
function App() {
return (
<GeocoreProvider config={{ apiKey: 'your-geocore-api-key' }}>
<YourApp />
</GeocoreProvider>
);
}
// Direct mode (API keys in the browser)
function App() {
return (
<GeocoreProvider config={{
apiKeys: {
mapbox: { publicToken: 'pk.eyJ1...' },
google: 'AIza...',
},
}}>
<YourApp />
</GeocoreProvider>
);
}Geocoding Hooks
useReverseGeocode — coordinates → display address
The simplest way to turn a lat/lng into a readable address. Uses the browser Geolocation API for auto-fetching device position.
import { useReverseGeocode, getDisplayAddress } from '@smarthivelabs-devs/geocore-react';
// Auto-detect user's browser location
function UserLocation({ geocore }) {
const { address, components, loading, error } = useReverseGeocode({
geocore,
autoFetch: true,
});
if (loading) return <p>Locating…</p>;
if (error) return <p>{error}</p>;
return <p>{address}</p>;
// → "Adum, Kumasi, Ashanti Region, Ghana"
}
// Geocode a map marker
function MarkerAddress({ geocore, markerCoords }) {
const { address, components } = useReverseGeocode({ geocore, coords: markerCoords });
return (
<div>
<p>{address}</p>
<p>{components.city}, {components.state}</p>
</div>
);
}useAddressSearch — debounced search with suggestions
Drop-in hook for address input fields. Handles debouncing, shows autocomplete suggestions, and locks in coordinates once the user selects a result.
import { useAddressSearch } from '@smarthivelabs-devs/geocore-react';
function AddressInput({ geocore, userCoords, onConfirm }) {
const search = useAddressSearch({
geocore,
proximity: userCoords,
limit: 5,
});
useEffect(() => {
if (search.confirmed && search.coords) {
onConfirm(search.value, search.coords);
}
}, [search.confirmed]);
return (
<div>
<input
value={search.value}
onChange={e => search.onChange(e.target.value)}
placeholder="Enter address…"
/>
{search.loading && <span>Searching…</span>}
{search.suggestions.map(s => (
<button key={s.address} onClick={() => search.onSelect(s)}>
<strong>{s.label}</strong>
{s.sublabel && <span>{s.sublabel}</span>}
</button>
))}
</div>
);
}useGeocoding
import { useGeocoding } from '@smarthivelabs-devs/geocore-react';
import { Geocore } from '@smarthivelabs-devs/geocore-react';
function AddressSearch({ geocore }: { geocore: Geocore }) {
const { geocodingResult, loading, error, geocode, reverse, reset } = useGeocoding(geocore);
return (
<div>
<button onClick={() => geocode('Eiffel Tower, Paris')}>Search</button>
{loading && <p>Searching...</p>}
{geocodingResult && (
<p>
{geocodingResult.data.formattedAddress}
{' — '}
{geocodingResult.data.coordinates.lat}, {geocodingResult.data.coordinates.lng}
</p>
)}
{error && <p>Error: {error.message}</p>}
</div>
);
}Community Places — "Can't find it? Pin it on the map"
Map providers often miss locally-known names, especially in places like Ghana ("Kaneshie First Light", "Circle", "Abossey Okai Spare Parts"). Community places let your users fix that: when a search finds nothing, they pin the spot on the map and name it. Geocore stores it, and later geocode() calls for that name are answered from Geocore before any provider is called.
How Geocore handles each contribution:
- No duplicates. A pin within ~75 m with a similar name confirms the existing place. A different name on the same spot (~25 m) is stored as an alias. Anything else creates a new place. Re-submitting from the same user does nothing (
action: 'duplicate'). - Visibility. A new place is searchable immediately by the project that added it. It becomes visible to every project once it is
verified: 3 distinct contributors, or 2 from different projects. PassexternalUserIdso each of your users counts separately. - Results. Community matches come back in the normal geocode shape with
provider: 'community',source: 'community', aconfidencescore andplaceId: 'gc_…'.reverse()uses a nearby community place as the POI name. Passcommunity: falseto skip community places.
useAddressSearch + contributeManual
import { useState } from 'react';
import { useAddressSearch, MapComponent } from '@smarthivelabs-devs/geocore-react';
function PickupInput({ geocore, user }) {
const search = useAddressSearch({ geocore });
const [pin, setPin] = useState<{ lat: number; lng: number } | null>(null);
return (
<div>
<input value={search.value} onChange={e => search.onChange(e.target.value)} />
{search.suggestions.map(s => (
<button key={s.address} onClick={() => search.onSelect(s)}>{s.label}</button>
))}
{search.notFound && (
<>
<p>Can't find "{search.lastQuery}"? Tap its location on the map.</p>
<MapComponent onMapClick={setPin} markers={pin ? [pin] : []} />
{pin && (
<button onClick={() => search.contributeManual(
search.lastQuery,
{ latitude: pin.lat, longitude: pin.lng },
{ externalUserId: user.id, countryCode: 'GH' },
)}>
Save "{search.lastQuery}" here
</button>
)}
</>
)}
</div>
);
}useContributePlace
Use this for a full pin flow: look for nearby places first, then confirm one or create a new one.
import { useContributePlace } from '@smarthivelabs-devs/geocore-react';
const { findNearby, confirm, contribute, nearby, result, loading, error } = useContributePlace(geocore);
await findNearby(pin.lat, pin.lng); // nearby.places → "Is it one of these?"
await confirm(nearby.places[0].id, { externalUserId: user.id });
await contribute({ name: 'Kaneshie First Light', lat: pin.lat, lng: pin.lng, category: 'junction', externalUserId: user.id });
// result.action → 'created' | 'confirmed' | 'alias_added' | 'duplicate'The geocore instance also exposes contributePlace, searchCommunityPlaces, nearbyCommunityPlaces, getCommunityPlace, confirmCommunityPlace and reportCommunityPlace. All of them require backend mode.
Directions Hook
useDirections
import { useDirections } from '@smarthivelabs-devs/geocore-react';
function RouteMap({ geocore }) {
const { result, loading, error, getDirections } = useDirections(geocore);
return (
<button onClick={() =>
getDirections(
{ lat: 51.5074, lng: -0.1278 },
{ lat: 48.8566, lng: 2.3522 },
{ mode: 'driving' }
)
}>
Get Route
</button>
);
}Places Hooks
usePlaces · useNearbySearch · useAutocomplete
import { usePlaces, useNearbySearch, useAutocomplete } from '@smarthivelabs-devs/geocore-react';
// Search by query
const { result, loading, searchPlaces } = usePlaces(geocore);
await searchPlaces('coffee', { lat: 51.5, lng: -0.12 }, { radius: 500 });
// Category search around a point
const { result, searchNearby } = useNearbySearch(geocore);
await searchNearby('restaurant', { lat: 51.5, lng: -0.12 });
// Autocomplete suggestions
const { predictions, loading, getSuggestions } = useAutocomplete(geocore);
await getSuggestions('Hyde Park Lo');Spatial Analysis Hooks
useElevation
import { useElevation } from '@smarthivelabs-devs/geocore-react';
const { result, loading, getElevation } = useElevation(geocore);
await getElevation(51.5074, -0.1278);
console.log(result?.data.elevation); // metresuseIsochrone
import { useIsochrone } from '@smarthivelabs-devs/geocore-react';
const { result, getIsochrone } = useIsochrone(geocore);
await getIsochrone(51.5074, -0.1278, [15, 30], { mode: 'walking' });
// result.data.features — GeoJSON FeatureCollectionuseTimezone
import { useTimezone } from '@smarthivelabs-devs/geocore-react';
const { result, getTimezone } = useTimezone(geocore);
await getTimezone(51.5074, -0.1278);
console.log(result?.data.timeZoneId); // 'Europe/London'Utility Hooks
useTraffic
import { useTraffic } from '@smarthivelabs-devs/geocore-react';
const { result, getTraffic } = useTraffic(geocore);
await getTraffic(51.5074, -0.1278);
console.log(result?.data.congestionLevel); // 'free' | 'light' | 'moderate' | 'heavy'useDistanceMatrix
import { useDistanceMatrix } from '@smarthivelabs-devs/geocore-react';
const { result, getMatrix } = useDistanceMatrix(geocore);
await getMatrix(['London, UK', 'Paris, France'], ['Berlin, Germany']);useSnapToRoad · useRouteOptimize · useStaticMap
import { useSnapToRoad, useRouteOptimize, useStaticMap } from '@smarthivelabs-devs/geocore-react';
const { result, snap } = useSnapToRoad(geocore);
const { result, optimise } = useRouteOptimize(geocore);
const { result, getMap } = useStaticMap(geocore);Weather Hook
import { useWeather } from '@smarthivelabs-devs/geocore-react';
function WeatherWidget({ geocore, lat, lng }) {
const { currentResult, forecastResult, loading, error, getWeather, getForecast } = useWeather(geocore);
useEffect(() => {
getWeather(lat, lng);
getForecast(lat, lng, 7);
}, [lat, lng]);
if (loading) return <p>Loading weather...</p>;
return (
<div>
<p>{currentResult?.data.temperature}°C — {currentResult?.data.description}</p>
{forecastResult?.data.days.map(day => (
<p key={day.date}>{day.date}: {day.tempMin}–{day.tempMax}°C</p>
))}
</div>
);
}Pricing Hook — SmartHive Pricing Engine
Converts a base price to the user's local currency. Detects country from GPS or accepts a manual override (country picker).
import { usePricing } from '@smarthivelabs-devs/geocore-react';
function PricingDisplay({ geocore, userLat, userLng }) {
const { result, loading, error, localizePrice, localizePriceByCountry } = usePricing(geocore);
// Auto-detect country from location
useEffect(() => {
localizePrice(100, 'GHS', userLat, userLng);
}, [userLat, userLng]);
// Manual override — user picks country from a dropdown
const handleCountryChange = (code: string) => {
localizePriceByCountry(100, 'GHS', code);
};
return (
<div>
{loading && <p>Calculating price...</p>}
{result && (
<p>
{result.data.symbol}{result.data.amount} {result.data.currency}
{' '}/month
</p>
)}
<select onChange={e => handleCountryChange(e.target.value)}>
<option value="US">United States</option>
<option value="NG">Nigeria</option>
<option value="GH">Ghana</option>
<option value="GB">United Kingdom</option>
</select>
</div>
);
}Direct FX rate lookup
const { rateResult, ratesResult, getRate, getRates } = usePricing(geocore);
await getRate('USD', 'EUR');
console.log(rateResult?.data.rate); // 0.92
await getRates('USD');
console.log(ratesResult?.data.rates); // { EUR: 0.92, GBP: 0.79, NGN: 1580, ... }Countries Hook — Country picker / catalog
List and look up ISO countries (name, currency, flag, region). Backend mode required.
import { useCountries } from '@smarthivelabs-devs/geocore-react';
function CountryPicker({ geocore }) {
const { listResult, loading, error, listCountries, getCountry } = useCountries(geocore);
useEffect(() => {
listCountries({ fields: ['code', 'name', 'flag', 'currencies'] });
}, []);
return (
<select disabled={loading} onChange={async (e) => {
const { country } = await getCountry(e.target.value);
console.log(country?.name, country?.primaryCurrency);
}}>
{(listResult?.countries ?? []).map((c) => (
<option key={c.code} value={c.code}>
{c.flag?.emoji} {c.name}
</option>
))}
</select>
);
}Company Intel Hook — Research & briefs
Cache-first company dossiers and AI-ready interview briefs. Backend mode required.
import { useCompanies } from '@smarthivelabs-devs/geocore-react';
function CompanyResearch({ geocore }) {
const {
researchResult,
briefResult,
loading,
error,
researchCompany,
getCompanyBrief,
} = useCompanies(geocore);
return (
<div>
<button
disabled={loading}
onClick={() => researchCompany({ query: 'Stripe', scope: 'web_news' })}
>
Research Stripe
</button>
{researchResult?.status === 'ok' && (
<>
<p>{researchResult.brief?.overview}</p>
<ul>
{(researchResult.brief?.interviewAngles ?? []).map((a) => (
<li key={a}>{a}</li>
))}
</ul>
</>
)}
<button onClick={() => getCompanyBrief('stripe', { scope: 'web_news' })}>
Load cached brief
</button>
{briefResult?.brief && <pre>{JSON.stringify(briefResult.brief, null, 2)}</pre>}
{error && <p>{error.message}</p>}
</div>
);
}Search Engine Hook
import { useSearch } from '@smarthivelabs-devs/geocore-react';
function SearchPanel({ geocore }) {
const { searchResult, jobResult, loading, search, getSearchJob } = useSearch(geocore);
return (
<button
disabled={loading}
onClick={async () => {
const r = await search({ query: 'OpenAI', vertical: 'company', scope: 'minimal' });
if (r.searchJobId) await getSearchJob(r.searchJobId);
}}
>
Search
</button>
);
}Error Handling
Every hook exposes an error: Error | null field. Errors are caught internally — they never propagate to your component's error boundary unless you rethrow them.
import { useGeocoding } from '@smarthivelabs-devs/geocore-react';
import { GeocoreError } from '@smarthivelabs-devs/geocore-react';
function AddressSearch({ geocore }) {
const { geocodingResult, loading, error, geocode } = useGeocoding(geocore);
return (
<div>
<button onClick={() => geocode('Unknown Place XYZ')}>Search</button>
{error && (
<p style={{ color: 'red' }}>
{error instanceof GeocoreError
? `${error.code}: ${error.message}`
: error.message}
</p>
)}
</div>
);
}Use reset() to clear error and result state before a new search:
const { geocode, reset, error } = useGeocoding(geocore);
const handleNewSearch = () => {
reset();
geocode('New Address');
};Context Hook
Access the Geocore instance anywhere inside GeocoreProvider:
import { useGeocoreConfig } from '@smarthivelabs-devs/geocore-react';
function AnyChildComponent() {
const { geocore } = useGeocoreConfig();
const { geocodingResult, geocode } = useGeocoding(geocore);
// ...
}Hook Return Shapes
All hooks return { loading: boolean, error: Error | null, reset: () => void } plus the result fields and action callbacks listed below:
| Hook | Result field(s) | Actions |
|------|----------------|---------|
| useGeocoding | geocodingResult, reverseResult | geocode(address, options?), reverse(lat, lng, options?) |
| useDirections | result | getDirections(from, to, options?) |
| usePlaces | result | searchPlaces(query, center, options?) |
| useNearbySearch | result | searchNearby(category, center, options?) |
| useAutocomplete | predictions | getSuggestions(query, options?) |
| useElevation | result | getElevation(lat, lng) |
| useIsochrone | result | getIsochrone(lat, lng, minutes[], options?) |
| useTimezone | result | getTimezone(lat, lng) |
| useTraffic | result | getTraffic(lat, lng, options?) |
| useDistanceMatrix | result | getMatrix(origins[], destinations[], options?) |
| useSnapToRoad | result | snap(points[]) |
| useRouteOptimize | result | optimise(waypoints[], options?) |
| useStaticMap | result | getMap(lat, lng, options?) |
| useWeather | currentResult, forecastResult | getWeather(lat, lng, options?), getForecast(lat, lng, days?, options?) |
| usePricing | result, rateResult, ratesResult | localizePrice(...), localizePriceByCountry(...), getRate(from, to), getRates(base) |
| useCountries | listResult, countryResult | listCountries(options?), getCountry(code, options?) |
| useCompanies | listResult, companyResult, briefResult, researchResult | listCompanies(), getCompany(slug), getCompanyBrief(slug), researchCompany(body) |
| useSearch | searchResult, jobResult | search(body), getSearchJob(id) |
| useProviders | providers, provider, operationProviders | getProviders(), getProvider(name), getProvidersForOperation(op) |
| useMap | map | createMap(options) |
Provider Hook
import { useProviders } from '@smarthivelabs-devs/geocore-react';
const { providers, loading, getProviders, getProvider, getProvidersForOperation } = useProviders(geocore);
await getProviders();
await getProvidersForOperation('geocode');Interactive Map Component
import { MapComponent } from '@smarthivelabs-devs/geocore-react';
<MapComponent
geocore={geocore}
center={{ lat: 51.5074, lng: -0.1278 }}
zoom={13}
markers={[
{ lat: 51.5074, lng: -0.1278, title: 'London' },
]}
onMarkerClick={(marker) => console.log(marker)}
/>All Hooks
| Hook | Returns / Actions | Notes |
|------|-------------------|-------|
| useReverseGeocode | address, components, coords, loading, error, refresh | New in 1.6 — uses navigator.geolocation |
| useAddressSearch | value, suggestions, confirmed, coords, onChange, onSelect, confirm, clear | New in 1.6 — debounced search |
| useGeocoding | geocode, reverse | |
| useDirections | getDirections | |
| usePlaces | searchPlaces | |
| useNearbySearch | searchNearby | |
| useAutocomplete | getSuggestions | |
| useElevation | getElevation | |
| useIsochrone | getIsochrone | |
| useTimezone | getTimezone | |
| useTraffic | getTraffic | |
| useDistanceMatrix | getMatrix | |
| useSnapToRoad | snap | |
| useRouteOptimize | optimise | |
| useStaticMap | getMap | |
| useWeather | getWeather, getForecast | |
| usePricing | localizePrice, localizePriceByCountry, getRate, getRates | |
| useCountries | listCountries, getCountry | New in 1.7 |
| useCompanies | listCompanies, getCompany, getCompanyBrief, researchCompany | New in 1.8 |
| useSearch | search, getSearchJob | New in 1.8 |
| useProviders | getProviders, getProvider, getProvidersForOperation | |
| useMap | createMap | |
Every hook exposes { loading, error, reset } alongside its action callbacks.
Phone numbers (hooks)
Headless hooks for phone fields — you build the UI, the hooks handle country
selection and search, as-you-type formatting and validation for every country,
offline. All phone functions from @smarthivelabs-devs/geocore-react/phone
(parsePhone, normalizePhone, formatPhone, getPhoneCountries, …) are
re-exported from this package too.
| Hook | Use it for |
|---|---|
| usePhoneInput(options) | A full phone field: text, formatting, country, picker search, validation |
| usePhoneCountries({ preferred, locale }) | Just the country list and search, for your own picker |
| usePhoneValidation(phone, { defaultCountry, requireMobile }) | Validating a number you already keep in state |
import { usePhoneInput } from '@smarthivelabs-devs/geocore-react';
function PhoneField({ value, onChange }) {
const phone = usePhoneInput({
value, // E.164, e.g. '+233241234567'
defaultCountry: 'GH', // otherwise guessed from the device locale
preferredCountries: ['GH', 'NG'],
requireMobile: true,
onChange: ({ e164 }) => onChange(e164 ?? ''),
});
return (
<>
{/* your country button: phone.selectedCountry.flag, .dialCode, .name */}
{/* your picker: phone.filteredCountries, phone.countryQuery / setCountryQuery, phone.setCountry(code) */}
<input type="tel" autoComplete="tel" value={phone.text} onChange={(e) => phone.setText(e.target.value)} />
{/* phone.errorMessage, phone.valid, phone.e164 */}
</>
);
}usePhoneInput returns text, setText, country, selectedCountry, setCountry,
result, e164, valid, isEmpty, errorMessage, countries, filteredCountries,
countryQuery, setCountryQuery, setValue and reset. Typing +44… switches the
country automatically. e164 is only set for a valid number — store that.
Changelog
1.9.0
- Phone hooks —
usePhoneInput,usePhoneCountries,usePhoneValidation(headless; bring your own UI). - All phone helpers are owned and exported directly by this package.
1.8.0
- New
useCompanieshook — research/list/brief company dossiers via Company Intel. - New
useSearchhook — generic search + job status. - Re-exports
CompanyRecord,CompanyBrief,CompanyResearchRequest, and related backend result types.
1.7.0
- New
useCountrieshook — list/look up ISO countries (currencies, flags, regions) via the Geocore countries catalog. - Re-exports
CatalogCountry,CountriesOptions, and related backend result types.
1.6.0
- New
useReverseGeocodehook — reverse-geocode usingnavigator.geolocationfor auto device position, or pass explicit coordinates. Returns normalizedaddressstring and structuredcomponents. - New
useAddressSearchhook — debounced address input with autocomplete suggestions and coordinate confirmation. - Normalized address components —
componentsfrom all hooks use consistent keys (city,state,area,street, etc.) regardless of provider. getDisplayAddressutility — re-exported from this package for convenience.
License
MIT — SmartHive Labs
IP Lookup Hook
const { countryCode, country, loading, error, lookup, reset } =
useIpLookup(geocore, { auto: true });
// Manual by default, including explicit-IP lookup:
await lookup('8.8.8.8');Set auto: true only when the app should resolve on mount. IP-derived locations are approximate.
Use the offline timezone alternative when an IP request is unnecessary:
const { countryCode, countryName, timezone, confidence, candidates, detect } =
useTimezoneCountry();Pass { timezone: 'Africa/Accra' } to override the browser timezone.
