Victor Jeman Academy

How do I get the user's current location?

Use the browser Geolocation API, ask permission over HTTPS, and keep a fallback ready for when the user says no.

The browser already knows the location

Call navigator.geolocation.getCurrentPosition with a success callback and an error callback. On success you get coords.latitude and coords.longitude.

Show me how to call navigator.geolocation.getCurrentPosition in a React component, store [latitude and longitude] in state, and center my [map library] on that point.

Permission and HTTPS are required

It only works on HTTPS (or localhost), and the browser prompts for permission the first time. You cannot read a position silently or grab it on page load, so trigger the request from a clear action like a "Find me" button.

My geolocation call works on localhost but not on my deployed site. Is this an HTTPS or a permission issue, and how do I confirm which from the [error code I am seeing]?

Always have a fallback for "no"

Plenty of users deny location, and the error callback fires when they do. Do not leave the map blank. Let them pick a point by clicking the map or typing an address, so the feature still works without their position.

When the user denies location (the error callback fires with [the permission denied code]), how do I fall back to letting them click the [map library] map to set their point manually?

Geolocation needs user permission and HTTPS, so trigger it from a button and always keep a manual pick-a-point fallback for when the user declines.

Additional Resources

Explore these carefully curated resources to deepen your understanding and practice the concepts covered in this lesson.