Use the person's location
Like the camera, the location of the person reaches your view only after two yeses: one in the webapp for your view and one in the browser. Ask when the person clicks, read the position and send the world no more than it needs. The example handles both a browser that cannot give a position and a person who says no.
jsx
import { useState } from 'react';
import { useWorld } from './useWorld.js';
// A fake city guide answers the position that the person sends.
const guide = { name: 'City guide', onMessage: (message) => `Looking for cafés near ${message.text}…` };
// The browser gives the position to callbacks, and this function turns it into a promise.
function currentPosition() {
return new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition(resolve, reject, { timeout: 10000 });
});
}
export default function App() {
// While building: the fake world (every feature allowed). In the webapp: useWorld()
const { world, error } = useWorld({ fake: { world: guide } });
const [note, setNote] = useState('Your location is not shared.');
if (error) return <p>Could not connect ({error.code}).</p>;
if (!world) return <p>Connecting…</p>;
// Asked only when the person wants it, never when the view opens.
async function shareLocation() {
try {
// First the yes in the webapp, for this view only (asked once), after which the view is loaded again.
if (!world.webapp.allowed.includes('geolocation')) {
await world.askFor(['geolocation']);
return;
}
// Then the browser asks its own question (the first time) and gives the position.
const { latitude, longitude } = (await currentPosition()).coords;
// Three decimals place the person within about 100 metres. Send no more than the world needs.
const where = `${latitude.toFixed(3)}, ${longitude.toFixed(3)}`;
setNote(`You are near ${where}.`);
await world.send(where);
} catch (error) {
// 'declined' means the person said no in the webapp. Any other error means the browser has no position.
setNote(error.code === 'declined'
? 'You said no: the view works without your location.'
: 'Your location is not available here.');
}
}
const last = world.messages.filter((message) => !message.fromMe).at(-1);
return (
<>
<button onClick={shareLocation}>Share my location</button>
<p>{note}</p>
<p>{last ? last.text : ''}</p>
</>
);
}js
import { connectToHost } from '@unaiverse/gui-kit';
// A fake city guide answers the position that the person sends.
const guide = { name: 'City guide', onMessage: (message) => `Looking for cafés near ${message.text}…` };
// The browser gives the position to callbacks, and this function turns it into a promise.
function currentPosition() {
return new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition(resolve, reject, { timeout: 10000 });
});
}
// While building: the fake world (every feature allowed). In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: guide } });
const share = document.createElement('button');
share.textContent = 'Share my location';
const note = document.createElement('p');
note.textContent = 'Your location is not shared.';
const answer = document.createElement('p');
document.body.append(share, note, answer);
// Asked only when the person wants it, never when the view opens.
share.onclick = async () => {
try {
// First the yes in the webapp, for this view only (asked once), after which the view is loaded again.
if (!world.webapp.allowed.includes('geolocation')) {
await world.askFor(['geolocation']);
return;
}
// Then the browser asks its own question (the first time) and gives the position.
const { latitude, longitude } = (await currentPosition()).coords;
// Three decimals place the person within about 100 metres. Send no more than the world needs.
const where = `${latitude.toFixed(3)}, ${longitude.toFixed(3)}`;
note.textContent = `You are near ${where}.`;
await world.send(where);
} catch (error) {
// 'declined' means the person said no in the webapp. Any other error means the browser has no position.
note.textContent = error.code === 'declined'
? 'You said no: the view works without your location.'
: 'Your location is not available here.';
}
};
// Called at once, then after every change of the world.
world.subscribe((node) => {
const last = node.messages.filter((message) => !message.fromMe).at(-1);
answer.textContent = last ? last.text : '';
});How it works
In the webapp the location is the feature 'geolocation'. Look for that name in world.webapp.allowed and request it with world.askFor(['geolocation']). After a yes the webapp loads your view again. Ask for the camera only when needed shows how the view resumes from there without a second click.
navigator.geolocation.getCurrentPositionpasses the position to a callback. The example wraps the call in aPromiseand passestimeout: 10000to make it reject after 10 seconds instead of leaving the person waiting.- Round latitude and longitude to the precision that the world needs or send a city typed in by the person.
- The check for
'declined'catches only a no given in the webapp. Errors of the browser have a numericcodeinstead (1 for a denied permission, 2 for an unavailable position, 3 for a timeout).