Skip to main content

Geolocation

· One min read
Rob Blackbourn

I had a play using the browser geolocation api to center the map on the location of the browser. You have to allow your browser to know your location for this to work.

import { useEffect, useState } from 'react'

import { Coordinate, Map, TileLayer } from '@jetblack/map'

export function Geolocation() {
const [center, setCenter] = useState<Coordinate>({
latitude: 51.47684676353231,
longitude: -0.0005261695762532147,
})
useEffect(() => {
navigator.geolocation.getCurrentPosition(
({ coords: { latitude, longitude } }) => setCenter({ latitude, longitude }),
error => console.log('error', error)
)
}, [])

return (
<div style={{ textAlign: 'center', marginTop: 50 }}>
<div style={{ margin: '0 auto' }}>
<Map center={center}>
<TileLayer />
</Map>
</div>
</div>
)
}