Usa la posizione della persona
Come la fotocamera, la posizione della persona arriva alla tua vista solo dopo due sì (uno nella webapp per la tua vista e uno nel browser). Chiedi quando la persona fa clic, leggi la posizione e invia al mondo solo quello che gli serve. L'esempio gestisce sia un browser che non sa dare la posizione sia una persona che dice di 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 : '';
});Come funziona
Nella webapp la posizione è la funzione 'geolocation' ed è con questo nome che la cerchi in world.webapp.allowed e la chiedi con world.askFor(['geolocation']). Dopo un sì la webapp carica di nuovo la tua vista. Chiedi la fotocamera solo quando serve mostra come la vista riparte da lì senza un secondo clic.
navigator.geolocation.getCurrentPositionpassa la posizione a una callback. L'esempio avvolge la chiamata in unaPromisee passatimeout: 10000in modo che venga rifiutata dopo 10 secondi invece di lasciare la persona ad aspettare.- Arrotonda latitudine e longitudine alla precisione che serve al mondo oppure invia al loro posto una città scritta dalla persona.
- Il controllo su
'declined'riconosce solo il no dato nella webapp. Gli errori del browser hanno invece uncodenumerico (1 per un permesso negato, 2 per una posizione non disponibile, 3 per un timeout).