The code samples used for this post can be found here.
geolocation API has a great level of compatibility of almost all browsers.
Therefore, with a simple TypeScript code, we can easily use the geolocation data.
NOTE: In order to use the
geolocationAPI, the device must be connected to the Internet. Also, each browser vendor uses its own mechanism to get geolocation data, which will cause different result even in the same device. This article gives us more details.
- ASP.NET Core App from the previous post
- Computer or mobile devices that can access to the Internet through Wi-Fi or mobile network
NOTE 1: We use
firstname.lastname@example.org this post. There are breaking changes on VueJs for TypeScript, so it’s always a good idea to check out the official guideline.
NOTE 2: Code samples used in this post were from the MDN document that was altered to fit in TypeScript.
In order to display latitude, longitude and altitude retrieved from the
geolocation API, we need to update the
That’s pretty much self descriptive – clicking or tapping the
Get Location button will display those geolocation data. Let’s move onto the logic side.
Get Location button is bound with the
getLocation() event, which needs to be implemented like below:
First of all, we need to declare properties for
altitude, followed by the
getLocation() method. Let’s dig into it.
- First of all, we check the
navigator.geolocationisntance if the web browser supports
geolocationAPI or not.
getCurrentPosition()method to get the current position. This method then passes two callback methods and an option instance as its parameters.
- Callback method,
success(), passes the
positioninstance containing current position details and binds co-ordinates to the browser.
error()callback handles error.
optionsinstance provides options for the
NOTE Each callback method has its return type, according to the type definition, which is not necessary. Therefore, we just return
options instance used above is actually an interface type of
PositonOptions that needs to be implemented. Its implementation might be looking like below:
We completed the TypeScript part. Let’s run the app!
When we use a web browser within our dev machine, it firstly asks us to get a permission to use our location data:
Allow and we’ll see the result.
This time, let’s do it on a mobile browser. This is taken from Chrome for iPhone. It also asks us a permission to use geolocation data.
Once tapping the
OK button, we can see the result.
So far, we’ve briefly looked at the
geolocation API to populate current location. That’s not that hard, isn’t it?
If we have more complex scenario, need more accurate location details, or need constant access to the location data even we’re not using the app, then native app might have to be considered. Here’s a good discussion regarding to these concerns. But using HTML5 geolocation API would be enough in majority of cases.