Recipe 14.4

Showing the Device Location on a Map

You can use the data from the Geocoding API to generate a map of the device’s location by integrating with external mapping services such as Google Maps.

This is an example of using the Google Maps Embed API to create an iframe with an embedded map.

Code

JavaScript
// Assuming you have a placeholder element in the page with the ID `map`
const map = document.querySelector('#map');

navigator.geolocation.getCurrentPosition(position => {
  const { latitude, longitude } = position.coords;

  // Adjust the iframe size as desired
  const iframe = document.createElement('iframe');
  iframe.width = 450;
  iframe.height = 250;

  // The map type is part of the URL path
  const url = new URL('https://www.google.com/maps/embed/v1/place');

  // The `key` parameter contains your API key
  url.searchParams.append('key', 'YOUR_GOOGLE_MAPS_API_KEY');

  // The `q` parameter contains the latitude and longitude coordinates
  // separated by a comma.
  url.searchParams.append('q', `${latitude},${longitude}`);
  iframe.src = url;

  map.appendChild(iframe);
});
Web API Cookbook
Joe Attardi