Routing — NativePHP Mobile plugin#
Real-route distance and travel time (ETA) from one origin to many destinations.
| Engine | Cost | Setup | |
|---|---|---|---|
| iOS | MapKit MKDirections (iOS 15+) |
free, on-device | none |
| Android | Mapbox, openrouteservice, Geoapify, Google or OSRM | your provider account | one key in the config |
Android has no free on-device routing engine, so routing there is opt-in and
server backed. Both platforms always answer: destinations that could not be
routed come back with ok: false and an error code, so an app falls back to a
straight-line (haversine) estimate on a signal instead of on a timeout that
never arrives.
Installation#
Routing is a premium plugin from the
NativePHP Plugin Marketplace.
After purchase it is served from the marketplace's private Composer
repository, so composer require alone will not find it: the repository and
your credentials have to be registered first.
# 1. the marketplace repository, in this projectcomposer config repositories.nativephp-plugins composer https://plugins.nativephp.com # 2. your credentials, on this machinecomposer config --global http-basic.plugins.nativephp.com <YOUR_EMAIL> <YOUR_LICENSE_KEY> # 3. the plugincomposer require guppylab/routing:"^4.3.1"php artisan native:plugin:register guppylab/routingphp artisan native:run # rebuild the native project
Your e-mail and licence key are under Purchased Plugins in your NativePHP dashboard.
Check it landed:
php artisan native:plugin:validate guppylab/routing
Runs on NativePHP Mobile 3 and 4 alike (nativephp/mobile ^3.0 and ^4.0),
tested on an iPhone with 4.6.0 and built for Android against both. NativePHP 4
itself needs PHP 8.4.
Keeping the credentials out of git#
--global is deliberate. Without it Composer writes them to auth.json in the
project root, where committing them is one git add . away. Globally they land
in your own Composer home and cannot be committed by accident. If you do want
them per project, add /auth.json to .gitignore first.
In CI, pass them through the environment instead of a file:
COMPOSER_AUTH='{"http-basic":{"plugins.nativephp.com":{"username":"<YOUR_EMAIL>","password":"<YOUR_LICENSE_KEY>"}}}'
Only composer install needs them. Once the package is in vendor/, nothing
in it talks to us: there is no licence check at runtime, no call home, and the
built app carries no key of ours.
Configuration#
Publish the config if you want to route on Android:
php artisan vendor:publish --tag=directions-config
# pick oneDIRECTIONS_ANDROID_PROVIDER=mapboxDIRECTIONS_MAPBOX_TOKEN=pk.…
Providers#
DIRECTIONS_ANDROID_PROVIDER |
Credential | Notes |
|---|---|---|
mapbox |
DIRECTIONS_MAPBOX_TOKEN |
Matrix API. Free tier is metered in elements (origins × destinations). |
ors |
DIRECTIONS_ORS_KEY |
openrouteservice. Results are CC-BY-SA and attribution is required — check both against your use. |
geoapify |
DIRECTIONS_GEOAPIFY_KEY |
Commercial use allowed on the free tier, with visible attribution. |
google |
DIRECTIONS_GOOGLE_KEY |
Routes computeRouteMatrix. Billed per element. |
osrm |
DIRECTIONS_OSRM_URL |
Your own osrm-backend, or any endpoint speaking its table/route shape. |
none |
— | Every destination comes back unsupported; fall back to a straight line. |
The credential is yours: billed to your account, governed by that provider's terms, and any attribution they require is your obligation to display. This plugin carries no quota and no key of its own.
Each provider also takes a DIRECTIONS_<PROVIDER>_URL. It is the whole
endpoint, not a prefix: set it and the plugin posts there instead of the
provider's own address, keeping that provider's request and response shape. It
exists to put a proxy or a test double in front of a provider, and is otherwise
left empty.
Upgrading from 3.x with a published config? Republish it. The provider blocks above are new in 4.0.0, and a config published on 3.x only has
osrm. Laravel'smergeConfigFromis shallow, so your file replaces the package'sandroidarray whole — you set a key, and every destination comes backunsupportedwith nothing to explain it.Copied!php artisan vendor:publish --tag=directions-config --force
A key in the config ships inside the app, where anyone holding the APK can read it. For production, prefer
osrmpointed at your own backend proxying a provider: the key stays on the server, results can be cached per area, and the provider can be swapped without a new release. See below.
There is deliberately no default URL. The public demo server
(router.project-osrm.org) is not allowed for production use by the OSRM
project, so the plugin will not quietly point your app at it. Run your own
osrm-backend, or leave the provider as none and use the fallback.
OSRM: one server, one profile#
A stock osrm-routed serves one profile and ignores the profile name in the
URL. Ask a car-only server for foot and it answers with car times, labelled
as walking. So:
# a separate server for walking (and cycling), when you have oneDIRECTIONS_OSRM_URL_WALKING=https://osrm-foot.example.comDIRECTIONS_OSRM_URL_CYCLING=https://osrm-bike.example.comDIRECTIONS_OSRM_PROFILE_CYCLING=bike # or no walking at all: it then reports unsupported instead of a car's timeDIRECTIONS_OSRM_PROFILE_WALKING=
The default keeps the 4.x behaviour (walking through url with the foot
profile), which is right for a proxy that dispatches on the profile name and
wrong for a single stock server.
Avoiding tolls and highways sends exclude=toll,motorway, which only works when
the server's profile defines those classes (the stock car.lua does). It is off
until you say your server takes it, DIRECTIONS_OSRM_EXCLUDE=true; a server
without them refuses the request, and from outside that looks like no route.
Pointing it at your own backend#
url does not have to be an osrm-backend instance — anything answering the
OSRM table/route shape will do, and your own API is usually the better
target:
device ──► https://api.example.com/routing/table/v1/driving/{coords} │ cache by area, rate limit, hold the provider key └──► OSRM, or a commercial matrix API
Three things this buys you. The provider key never ships in the bundle, where anyone holding the APK can read it. Results can be cached per area, and users cluster, so a handful of upstream calls serves a whole city. And the upstream provider can be swapped without a new release.
Authenticate against it with headers:
DIRECTIONS_OSRM_URL=https://api.example.com/routingDIRECTIONS_OSRM_TOKEN=a-scoped-revocable-token
// config/directions.php'headers' => array_filter([ 'Authorization' => env('DIRECTIONS_OSRM_TOKEN') ? 'Bearer '.env('DIRECTIONS_OSRM_TOKEN') : null,]),
Whatever goes in headers is readable by whoever holds the build, so it should
be a credential scoped to that endpoint and revocable on its own — never a
provider key you would not hand out. Android refuses to send these over plain
http to a routable host (the request still goes out unauthenticated, so you
get a 401 rather than a silent leak); http to a loopback or private address
stays allowed for local development.
Usage (PHP / Livewire)#
use Guppylab\Directions\Facades\Directions;use Guppylab\Directions\Events\DistancesReceived;use Native\Mobile\Attributes\OnNative; class NearbyStores extends \Livewire\Component{ public array $etas = []; public function calculate(): void { Directions::distances(-23.5505, -46.6333, [ ['id' => 1, 'lat' => -23.5614, 'lng' => -46.6559], ['id' => 2, 'lat' => -23.5880, 'lng' => -46.6820], ]); } #[OnNative(DistancesReceived::class)] public function onDistances(string $results = '[]', ?string $id = null): void { $event = new DistancesReceived($results, $id); if ($event->failed()) { $this->etas = $this->haversineFallback(); return; } $this->etas = $event->routed(); }}
Take the values, not the event object.
#[OnNative]is a Livewire listener, and Livewire calls it with the event's payload spread as named arguments. Type the parameter asDistancesReceivedand Livewire resolves it from the container instead: the method runs, no error is raised, and the object holds its constructor defaults —resultsis'[]'.failed()then answers true for a batch that worked, and every ETA quietly falls back to a straight line. Takestring $resultsand build the event yourself, as above.The event object is also dispatched server-side as a plain Laravel event, and there it arrives filled in. Where that fits better, listen for it:
Copied!Event::listen(DistancesReceived::class, function (DistancesReceived $event) {$event->routed();});
distances() returns the correlation id it sent (a UUID when you do not pass
one), so concurrent calls can be told apart by the $id parameter.
Check support up front to hide an ETA column instead of rendering empty cells:
Directions::isSupported(); // boolDirections::support(); // ['supported' => bool, 'provider' => 'mapkit'|'osrm'|'none']
Route options#
use Guppylab\Directions\Directions as Routing; // the constantsuse Guppylab\Directions\Facades\Directions; Directions::distances($lat, $lng, $stores, transport: Routing::TRANSIT, // AUTOMOBILE, WALKING, CYCLING, TRANSIT departure: new DateTimeImmutable('today 18:00'), // or arrival: ..., not both avoid: [Routing::AVOID_TOLLS], // and/or AVOID_HIGHWAYS);
departure predicts traffic for that time; arrival (iOS only) answers "leave
when, to be there by 9". Not every engine takes every option, so ask first and
show only what works:
Directions::support();// ['supported' => true, 'provider' => 'mapkit',// 'transports' => ['automobile', 'walking', 'cycling', 'transit'],// 'avoid' => true, 'departure' => true, 'arrival' => true]
| Cycling | Transit | Avoid tolls / highways | Departure | Arrival | |
|---|---|---|---|---|---|
| iOS (MapKit) | ✅ where Apple has the data | ✅ travel time only | ✅ iOS 16+ | ✅ | ✅ |
| Android, OSRM | with its own profile or server | — | opt-in, DIRECTIONS_OSRM_EXCLUDE |
— | — |
| Android, Mapbox | ✅ | — | — | — | — |
| Android, openrouteservice | ✅ | — | — | — | — |
| Android, Geoapify | ✅ | — | ✅ | — | — |
| Android, Google | ✅ | ✅ | ✅ (driving) | ✅ | — |
An option an engine cannot honour is never dropped quietly. Every row comes
back ok: false, error: 'unsupported' and a reason — transport, avoid,
departure or arrival. Ignoring it would return a plausible time for a route
nobody asked for: through the toll road, or a car's time labelled as walking.
What the iOS column means in practice, measured on an iPhone from São Paulo:
- Transit answers with real travel times (MapKit has São Paulo's buses and metro), but only times: MapKit gives transit ETAs, not transit routes.
- Cycling came back
no_routefor every destination: Apple has cycling data for some cities only, and São Paulo is not one of them.support()still lists it, because that depends on the city, not on the device. - Avoid tolls, São Paulo → Campinas by car: 71 min and 95 km with tolls, 129 min and 139 km without.
- Departure at 18:00 turned a 12-minute drive into 34.
Navigate there#
Once the list is sorted, the next tap is usually "take me there". Hand the destination to the navigation app the user already trusts and let it do turn-by-turn:
use Guppylab\Directions\Facades\Directions; public function navigateTo(int $storeId): void{ $store = Store::findOrFail($storeId); Directions::navigate($store->lat, $store->lng, label: $store->name);}
The constants below live on Guppylab\Directions\Directions; the plain strings
('ask', 'google', 'waze', 'apple') work too.
app: |
iOS | Android |
|---|---|---|
Directions::ASK (default) |
A sheet with Apple Maps, plus Google Maps and Waze when installed. Only Apple Maps? It opens straight away. | The system chooser over a geo: link: every map app installed. |
Directions::GOOGLE_MAPS |
Google Maps app, or its web version when missing | same |
Directions::WAZE |
Waze app, or its web version when missing | same |
Directions::APPLE_MAPS |
Apple Maps | not on Android: behaves as ASK |
A named app that is not installed opens its web version, so a tap never goes
nowhere. One difference to know about: on Android, ASK goes through a geo:
link, which opens the place in the chosen app with its Directions button one
tap away; a named app (GOOGLE_MAPS, WAZE) opens straight into directions. transport: Directions::WALKING is passed to Apple Maps and Google
Maps; Waze routes by car only.
Where the route starts. Without from, at the user's location, which is
what someone tapping a store wants. Pass from to start somewhere else, like
the hotel or the pickup point:
Directions::navigate($store->lat, $store->lng, label: $store->name, from: ['lat' => -23.5505, 'lng' => -46.6333]);
Apple Maps and Google Maps honour from. Waze and the Android chooser take
only a destination and ignore it, so do not build a flow that depends on it
there.
Street names instead of coordinates in Google Maps. Google Maps' links take no name next to a coordinate, so a destination sent as numbers is shown as numbers. When you have the street address, pass it and Google shows (and routes to) that; Apple Maps and Waze keep the exact coordinate:
Directions::navigate($store->lat, $store->lng, label: $store->name, address: $store->address, from: ['lat' => $hotel->lat, 'lng' => $hotel->lng, 'address' => $hotel->address]);
With an address, Google decides the final point, so keep it real and complete; leave it out and the exact coordinate is used.
The sheet and the chooser are system UI inside your app, so their words are yours. Set them in your app's language:
DIRECTIONS_NAVIGATION_CANCEL=CancelarDIRECTIONS_NAVIGATION_CHOOSER="Abrir com"
iOS: nothing to add to Info.plist. Asking iOS whether Google Maps or Waze is installed needs their schemes in
LSApplicationQueriesSchemes; the plugin declarescomgooglemapsandwazefor you and NativePHP merges them into the app at build time. If you also list schemes of your own, both lists are kept.
Search places#
Let people pick an origin or a destination by typing: "Av. Paulista 1000",
"Hotel Unique", "Allianz Parque". Every result carries its coordinate, ready for
distances(), navigate() or from.
use Guppylab\Directions\Events\AddressFound;use Guppylab\Directions\Events\PlacesFound;use Guppylab\Directions\Facades\Directions;use Native\Mobile\Attributes\OnNative; public string $search = '';public array $suggestions = []; // <input wire:model.live.debounce.400ms="search">public function updatedSearch(): void{ Directions::searchPlaces($this->search, near: ['lat' => -23.55, 'lng' => -46.63]);} #[OnNative(PlacesFound::class)]public function onPlaces(string $results = '[]', ?string $id = null, ?string $query = null, ?string $error = null): void{ // A slow answer to an older keystroke must not overwrite the current one. if ($query !== trim($this->search)) { return; } $this->suggestions = (new PlacesFound($results, $id, $query, $error))->places(); // [['title' => 'Rua Palestra Itália, 200', 'subtitle' => 'Água Branca, São Paulo', // 'lat' => -23.527, 'lng' => -46.678, 'city' => ..., 'state' => ..., 'postal_code' => ..., 'country_code' => 'BR'], ...]}
And the other way round, the address of a coordinate (a GPS fix, a tapped pin), in the same shape:
Directions::reverseGeocode($lat, $lng); #[OnNative(AddressFound::class)]public function onAddress(string $result = 'null', ?string $id = null, ?string $error = null): void{ $place = (new AddressFound($result, $id, $error))->place(); // or null when nothing is there}
| Without configuring anything | With your routing provider | |
|---|---|---|
| iOS | MapKit: on the device, free, addresses and businesses | not needed |
| Android | The built-in geocoder: addresses, no business names, and not on every device (then error: 'unsupported') |
Mapbox, Geoapify and openrouteservice autocomplete; Google Places Text Search, which also finds businesses |
The Android search reuses the key you set for routing, never its url: that
points at your routing endpoint, not at a search service.
Debounce, and mind the bill. On Android with a provider every call is an HTTP request against your quota; with Google, a billed Text Search. Use
wire:model.live.debounceand a minimum length before searching.
Call it once the page is live, not from
mount(). The answer is an event to the page, and a cached geocoder can answer in milliseconds, before the page listens; that event is gone without an error. Search on input, look up an address after a tap or a short moment after load.
error separates "could not search" from "found nothing": unsupported (no
geocoder and no provider) and failed (network, key, quota) come with an empty
list, and an empty list with no error means nothing matched.
Usage (JavaScript / Inertia — Vue or React)#
import { distances, navigate, onDistances, onPlaces, searchPlaces, setProvider } from 'guppylab-plugin-directions'; // JavaScript cannot read config/directions.php. Share it from the server// (an Inertia prop, a meta tag) and hand it over once at boot:setProvider(page.props.directionsProvider); // Directions::providerConfig() in PHP const unsubscribe = onDistances((rows, id) => { rows.filter((row) => row.ok); // { id, meters, seconds, ok } rows.filter((row) => !row.ok); // { id, ok: false, error }}); await distances(-23.5505, -46.6333, [ { id: 1, lat: -23.5614, lng: -46.6559 },]); // Hand a row to a navigation app (see "Navigate there" above).await navigate(-23.5614, -46.6559, { label: 'Av. Paulista', app: 'ask' }); // Search places (see "Search places" above).onPlaces((places, { query, error }) => { /* places[0].title, .lat, .lng */ });await searchPlaces('Allianz Parque', { near: { lat: -23.55, lng: -46.63 } });
The JS library ships TypeScript definitions and works across Livewire v3/v4 and Inertia (Vue/React).
Result contract#
Every destination you pass appears exactly once in the result.
[ { "id": "1", "meters": 4312, "seconds": 780, "ok": true }, { "id": "2", "ok": false, "error": "no_route" }]
error |
Meaning |
|---|---|
unsupported |
No routing engine available (Android without a provider), or an option the engine cannot honour — then reason says which: transport, avoid, departure, arrival |
timeout |
The engine did not answer within directions.timeout |
over_limit |
Dropped because the batch exceeded directions.max_destinations |
no_route |
The engine answered but found no route |
failed |
The engine returned an error |
Rows that failed on iOS also carry detail, the raw MapKit error ("MKErrorDomain 3"),
for diagnosis. It is not part of the contract.
Notes on each platform#
iOS. MKDirections is rate limited, so destinations are resolved one at a
time, each with its own timeout and a retry. Past roughly 50 calculations a
minute MapKit answers loadingThrottled (code 3); those wait 2.5 s, then 5 s,
then 7.5 s before giving up, inside the same timeout. A list recalculated on
every filter change will meet that limit: debounce, and cache what you can. Measured on an iPhone XR:
3 destinations in 2.3s, 11 in 8.2s, 25 in 14.4s. max_destinations defaults to
25.
How
no_routeis decided on iOS. MapKit does not report an unroutable destination asdirectionsNotFound, as you would expect. Measured with a destination in Lisbon from São Paulo, it answersMKError.serverFailure(code 2) — on both attempts. That name also covers a genuine outage, and nothing in the error separates the two.So the plugin reads a
serverFailurethat survived the retry asno_route. A transient outage usually clears on the second attempt; a pair of points with no road between them never does. The alternative was leavingno_routeunreachable on iOS, which would mean an app written against the contract above never sees a value the contract promises.
loadingThrottledanddecodingFailedstayfailed, because those are transient in a way retrying the batch can fix.
Android. The OSRM table service answers the whole batch in one request.
Servers may disable it or cap max-table-size, in which case the plugin falls
back to one /route request per destination. Requires INTERNET, which the
plugin declares. There is no on-device alternative: Play Services Location only
positions, the Maps SDK only renders, and the google.navigation: intent hands
the user to the Maps app without returning anything to you.
License#
Commercial. Version 4.0.0 onwards is a paid plugin — see LICENSE.
Versions up to 3.0.0 were released under MIT (LICENSE-MIT-v3). They are no longer distributed; copies already obtained keep their MIT rights.