SPRINT 3 ‐ Map Page - BlueJayBird11/UniJet GitHub Wiki
The goal for this user story is to create a Map Page with a simple map displaying the user's current location. We will use the Leaflet API for displaying the map.
First, you will need to follow the instructions for creating a new page as usual. Refer to the Profile Page documentation for a guide on this.
Next, it is crucial that you properly install and import Leaflet. After installed, you should add these imports to your index.tsx of the map directory.
import { MapContainer, TileLayer, Marker, Popup } from 'react-leaflet';
import "leaflet/dist/leaflet.css";
Once the Leaflet API is properly imported, you must retrieve the user's current geolocation. The position
state variable is updated with the latitude and longitude coordinates of the user's current location.
const [position, setPosition] = useState<[number, number] | null>(null);
useEffect(() => {
if ('geolocation' in navigator) {
navigator.geolocation.getCurrentPosition((position) => {
setPosition([position.coords.latitude, position.coords.longitude]);
});
}
}, []);
Next, we need to render the map. We will use MapContainer
from react-leaflet
. The map is centered on the user's current location (position
) with a zoom level of 13. For the brief second before the map first loads in, the "Loading..." text is displayed. width
and height
are used to set the full map's width and height.
if (!position) {
return <div>Loading...</div>;
}
return (
<div className="h-screen">
<MapContainer style={{ width: '100%', height: '86.6%' }} center={position} zoom={13} scrollWheelZoom={true}>
{/* Map Layers */}
</MapContainer>
</div>
);
Next, it is important to set the map layers. A tile layer from OpenStreetMap is used to provide the base map tiles (TileLayer
). Map tiles are loaded from the specified URL with attribution to OpenStreetMap contributors.
<TileLayer
attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
Lastly, you will set the user marker and pop-up. A marker (Marker
) is placed at the user's location, and a pop-up (Popup
) is attached to that marker indicating "You are here."
<Marker position={position}>
<Popup>You are here</Popup>
</Marker>
After everything is implemented, your map should look like this:
It is zoomable and scrollable.