Edit

Google Maps

google1

Map with tiles from Google Maps

This example demonstrates how to display tiles from Google's Map Tiles API in a map. To use the Google Map Tiles API, you need to set up a Google Cloud project and create an API key for your application. See the Map Tiles API documentation for instructions.
The ol/source/Google source can be used with a tile layer and is configured by passing properties to the constructor that are used in creating the session token request for accessing the tiles. The mapType defaults to 'roadmap' and can be changed to any of the supported map types.
When using the Google source, please make sure you comply with the Google Map Tiles API Policies, by adding the Google logo in the bottom-left corner of the map. You can add the logo as a static image by using a custom OpenLayers control, as shown in the example below.

main.js
import Google from 'ol/source/Google.js';
import Layer from 'ol/layer/WebGLTile.js';
import Map from 'ol/Map.js';
import View from 'ol/View.js';
import {Control, defaults as defaultControls} from 'ol/control.js';

function showMap(key) {
  const source = new Google({
    key,
    scale: 'scaleFactor2x',
    highDpi: true,
  });

  source.on('change', () => {
    if (source.getState() === 'error') {
      alert(source.getError());
    }
  });

  class GoogleLogoControl extends Control {
    constructor() {
      const element = document.createElement('img');
      element.style.pointerEvents = 'none';
      element.style.position = 'absolute';
      element.style.bottom = '5px';
      element.style.left = '5px';
      element.src =
        'https://developers.google.com/static/maps/documentation/images/google_on_white.png';
      super({
        element: element,
      });
    }
  }

  const map = new Map({
    layers: [new Layer({source})],
    controls: defaultControls().extend([new GoogleLogoControl()]),
    target: 'map',
    view: new View({
      center: [0, 0],
      zoom: 2,
    }),
  });
}

document.getElementById('key-form').addEventListener('submit', (event) => {
  showMap(event.target.elements['key'].value);
});
index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Google Maps</title>
    <link rel="stylesheet" href="node_modules/ol/ol.css">
    <style>
      .map {
        width: 100%;
        height: 400px;
      }
    </style>
  </head>
  <body>
    <div id="map" class="map">
      <dialog open>
        <form method="dialog" id="key-form">
          <label>Your API key
            <input type="password" name="key">
          </label>
          <button type="submit">show map</button>
        </form>
      </dialog>
    </div>


    <script type="module" src="main.js"></script>
  </body>
</html>
package.json
{
  "name": "google",
  "dependencies": {
    "ol": "9.1.0"
  },
  "devDependencies": {
    "vite": "^3.2.3"
  },
  "scripts": {
    "start": "vite",
    "build": "vite build"
  }
}