Saturday, October 22, 2016

[VB.NET] Get current device location on Windows 10

As for first write up, I'm gonna share what I have found while doing some projects. It's good to share something. Maybe it can be useful to someone who needed something like this as their task. Let's get started!


My development tools:-
1) Visual Studio 2015

2) Windows 10
3) Location turn on ("PC Settings --> Privacy --> Location")

1. Open VS2015 and create new project for Visual Basic [Console Application]
2. Right click on "Reference" under "Solution Explorer" tab and select "Add Reference.."
3. Search assemblies of "System.Device". Check on the box and click button OK to add the selected assemblies to Reference.
4. Add new item with keyboard shortcut "Ctrl + Shift + A". Search for text file, rename to something that can relate to configuration / settings. In my case, I rename to "config.txt". A textfile will be on my solutions. Double click to open up the file in editor. Enter below settings:-


5. To make your textfile can be editable without entering into source code, right click textfile that you have created earlier and select "Properties"
6. On "Copy to Output Directory", select "Copy Always". This will make the file visible on your debug folder.
7. It's time to read the textfile. Below are the function to read information from text file:



8. Now, we gonna test to run it on every interval seconds. Interval in VB.NET require a milliseconds format, so we gonna get from textfile and times with 1000. Below is how this device locator start and repeat every 3 seconds.



I'm using Threading.Thread.Sleep because I'm doing it in Main(). If I'm using Task.Delay(IntervalTime), it's not like going to works because the equal things to Threading.Thread.Sleep(milliseconds) in VS2013 and above is Await Task.Delay(milliseconds) which it will await the task to be complete in the interval before proceed to next line of code.

Ok, I can simply paste the code in here but I don't know how to format the code snippet like other software forumn does. Hahaa!

The output from this code consist of:-
1) Latitude
2) Longitude
3) Distance (current location and previous 3 seconds which suite for moving devices)
4) Address of the location. Address might not accurate as it will get the nearby address. For me, it just +- 10 metre so my address shown on my console is my next door neighbour address. Nevermind, still next door.

So, here I share the source code for download and use it wisely. Good luck!