Get GPS Coordinates & Generate Map In Javascript (Simple Example)

Welcome to a tutorial on how to get the GPS coordinates using Javascript, and display them on a map. It is not a mystery by now that there is something called the global positioning system (GPS), and it is very commonly used on mobile devices. But there is one thing that some beginners are still confused about – Nope, GPS is not a “native-app-only” feature.

  • To get the GPS coordinates in Javascript, we can use the Geolocation API – navigator.geolocation.getCurrentPosition()
  • Thereafter, draw the map using services such as Google Maps, Mapbox, or OpenLayers.

To better illustrate, let us walk through a simple example in this guide – Read on!

ⓘ I have included a zip file with all the example source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

QUICK SLIDES

 

 

TABLE OF CONTENTS

Download & Demo GPS & Map  Useful Bits & Links
The End

 

DOWNLOAD & DEMO

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

  • Register and get your own access key with Mapbox, insert it into section A of  3-gps-map.js.
  • That’s all. Launch 2-gps-map.html in your browser.
If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

 

THE DEMO

Your GPS reads: 0, 0

 

GET GPS & GENERATE MAP

All right, let us now get into the example of how to get the GPS coordinates and draw a map thereafter.

 

STEP 1) REGISTER & CREATE ACCESS TOKEN AT MAPBOX

First, register with Mapbox and get your own access token. For you guys who are worried that Mapbox might be some “shady company” – They are the ones behind the maps on Facebook and Snapchat.

 

 

STEP 2) THE HTML

2-gps-map.html
<!-- (A) LOAD MAPBOX API -->
<!-- https://www.mapbox.com/ | https://docs.mapbox.com/ -->
<script src="https://api.mapbox.com/mapbox-gl-js/v2.3.1/mapbox-gl.js"></script>
<link href="https://api.mapbox.com/mapbox-gl-js/v2.3.1/mapbox-gl.css" rel="stylesheet"/>
 
<!-- (B) CONTAINER TO RENDER MAP -->
<div id="map" style="width:100%; height:400px;"></div>

This should be self-explanatory. Just load the Mapbox API, and create a <div> to generate the map.

 

STEP 3) THE JAVASCRIPT

3-gps-map.js
// (A) INSERT ACCESS TOKEN HERE!
mapboxgl.accessToken = "TOKEN";
 
// (B) GET GPS COORDINATES
navigator.geolocation.getCurrentPosition(
  // (B1) DRAW MAP
  (pos) => {
    // THE MAP
    let map = new mapboxgl.Map({
      container: "map",
      style: "mapbox://styles/mapbox/streets-v11",
      center: [pos.coords.longitude, pos.coords.latitude],
      zoom: 13
    });
    // ADD A MARKER
    let marker = new mapboxgl.Marker()
      .setLngLat([pos.coords.longitude, pos.coords.latitude])
      .addTo(map);
  },
 
  // (B2) ON FAILING TO GET GPS COORDINATES
  (err) => { console.error(err); },
 
  // (B3) GPS OPTIONS
  {
    enableHighAccuracy: true,
    timeout: 5000,
    maximumAge: 0
  }
);

Keep calm and look closely. The Javascript is as straightforward as can be.

  • (A) Insert your access key here.
  • (B1) Get the GPS coordinates navigator.geolocation.getCurrentPosition, then draw the map new mapboxgl.Map().
  • (B2) Take note, once the user denies permission to access GPS, navigator.geolocation.getCurrentPosition() will not prompt again but throws an error. This is a good place to serve your “this app requires GPS” notice, and how to manually enable GPS.
  • (B3) The GPS options.

That’s all. But this is only the raw basics, read the Mapbox API documentation for more.

 

 

USEFUL BITS & LINKS

That’s all for this guide, and here is a small section on some extras and links that may be useful to you.

 

WHAT HAPPENED TO GOOGLE MAPS?

For you guys who are wondering, why not the almighty Google Maps? I have one word to describe the situation at the time of writing – Paywall. Yes, in order to access Google Maps API, one has to create a billing account, the credit card comes first.

It is definitely a lot of trouble for the younger developers and students who don’t have credit cards. So the next best free alternative is OpenStreetMap – Mapbox is one of the most credible companies that adopt OpenStreetMap and I will recommend a few more below.

P.S. Not saying that Google Maps is bad, but it’s really more of a viable option if you have a larger audience. OpenStreetMap is not totally free either, the API by various providers will cut after a certain number of requests.

 

MAP SERVICES

 

COMPATIBILITY CHECKS

This example will work on all modern browsers with a GPS unit (will give approximate GPS from the IP address if not).

 

LINKS & REFERENCES

 

YOUTUBE TUTORIAL

 

INFOGRAPHIC CHEAT SHEET

How to Get GPS Coordinates in Javascript (click to enlarge)

 

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *