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!

 

 

TABLE OF CONTENTS

 

 

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.

 

THE DEMO

Your GPS reads: 0, 0

 

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.9.1/mapbox-gl.js"></script>
<link href="https://api.mapbox.com/mapbox-gl-js/v2.9.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 => {
    // (B1-1) THE MAP
    let map = new mapboxgl.Map({
      container: "map",
      style: "mapbox://styles/mapbox/streets-v11",
      center: [pos.coords.longitude, pos.coords.latitude],
      zoom: 13
    });
 
    // (B1-2) 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.

 

 

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

 

SORRY FOR THE ADS...

But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.

Buy Me A Coffee Code Boxx eBooks

 

EXAMPLE CODE DOWNLOAD

Click here for 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.

 

EXTRA 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

 

TUTORIAL VIDEO

 

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!

4 thoughts on “Get GPS Coordinates & Generate Map In Javascript (Simple Example)”

    1. If you mean “can IP address be changed for testing” – Yes, just do a search for “location spoof developer tools chrome/firefox/edge”.

  1. Hi
    Spent a couple of hours on your site today reading and learning and testing out your download projects. This one on my webserver just generates a blank html page.
    Anyhow thanks for a excellent read and spending your time creating the examples.

    Cheers

Leave a Comment

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