Get GPS Coordinates & Draw Map In HTML Javascript

Once upon a time, Master Coffee asked a student to create a web app to “get the GPS coordinates and draw a map”. She immediately went into a deep trance and foamed in the mouth… A common symptom of overthinking. It is actually very easy in modern Javascript, let us walk through an example – Let’s go!

 

CODE DOWNLOAD

I have released this under the MIT license, feel free to use it in your own project – Personal or commercial. Some form of credits will be nice though. 🙂

 

 

VIDEO TUTORIAL

 

DEMO – GET GPS & DRAW MAP

Click on “start” to launch the demo. Allow access to your location, or this demo will not work… If you have accidentally denied location permission, see “I denied location access” below.

 

 

PART 1) REGISTER WITH MAPBOX (GET YOUR ACCESS TOKEN)

There are quite a number of map services in the world. But for this tutorial, we will be using Mapbox. Go ahead, register with them and get your access token – It’s free. Not sponsored by the way.

 

 

PART 2) THE HTML – MAP PAGE

gps-map.html
<!-- (PART A) LOAD MAPBOX API -->
<!-- https://docs.mapbox.com/ -->
<link href="https://api.mapbox.com/mapbox-gl-js/v3.2.0/mapbox-gl.css" rel="stylesheet">
<script src="https://api.mapbox.com/mapbox-gl-js/v3.2.0/mapbox-gl.js"></script>
<script defer src="gps-map.js"></script>
 
<!-- (PART B) MAP CONTAINER -->
<div id="demo"></div>

The HTML is as simple as it gets, we only need 2 things:

  1. Load the Mapbox API. You may want to read their documentation, load the latest version, and check out all the “good stuff” they offer.
  2. Create an empty <div> to draw the map in.

 

 

PART 3) THE JAVASCRIPT – GET GPS & DRAW MAP

gps-map.js
window.addEventListener("load", navigator.geolocation.getCurrentPosition(
  // (PARAM A) FUNCTION - DO SOMETHING ON SUCCESS
  gps => {
    // (A1) MAPBOX ACCESS TOKEN
    mapboxgl.accessToken = "YOUR-TOKEN";
 
    // (A2) DRAW MAP
    const pos = [gps.coords.longitude, gps.coords.latitude],
    map = new mapboxgl.Map({
      container: "demo",
      style: "mapbox://styles/mapbox/streets-v11",
      center: pos,
      zoom: 13
    });
 
    // (A3) ADD MARKER TO MAP
    new mapboxgl.Marker()
    .setLngLat(pos)
    .addTo(map);
  },
 
  // (PARAM B) FUNCTION - OPTIONAL, HANDLE ERRORS
  err => console.error(err),
 
  // (PARAM C) OBJECT - OPTIONAL, GPS OPTIONS
  {
    maximumAge: 0,
    timeout: 10000,
    enableHighAccuracy: true
  }
));

If you are a “panicking beginner”, keep calm and drink coffee.

  • On window load, we use navigator.geolocation.getCurrentPosition() to get the user’s GPS coordinates.
  • getCurrentPosition() takes in 3 parameters.
    • (PARAM A) The first one is a function that will run on successfully getting the GPS coordinates. We will use the Mapbox API in this one to draw the map.
    • (PARAM B) Optional, a function to handle errors. Here, we just output the error to the console.
    • (PARAM C) Optional, GPS options. Pretty straightforward, but check out the documentation on MDN if you need more info.

P.S. Remember to insert your access token in (A1).

 

 

I DENIED LOCATION ACCESS

  • If you have denied location access permission, the browser will not ask again.
  • The only way is to manually change the permission – In most browsers, click on the icon beside the URL and enable “location”.

 

 

CHECK FOR LOCATION ACCESS PERMISSION

gps-map-check.js
// (PARAM B) FUNCTION - OPTIONAL, HANDLE ERRORS
err => {
  console.log(err);
  navigator.permissions.query({ name: "geolocation" })
  .then(res => {
    if (res.state == "denied") { alert("Manually allow location access"); }
  });
},
  • If you want to display a “please enable location access” message, a good place is to modify the “handle error” function.
  • Use the Permissions API to check for geolocation access. If it is denied, display the message.

 

 

THE END – OTHER MAP SERVICES

That’s all for this quick tutorial. But before we end, Mapbox is not the only map service in the world. Feel free to switch to a map service of your choice, here are a few common ones:

 

CHEAT SHEET

Get GPS Coordinates & Draw Map in HTML Javascript (click to enlarge)