Geocoding in MapLibre

by Mapycz

HTML

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>Geocoding in MapLibre</title>
    <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />
    <script src="https://unpkg.com/maplibre-gl@2.4.0/dist/maplibre-gl.js"></script>
    <link href="https://unpkg.com/maplibre-gl@2.4.0/dist/maplibre-gl.css" rel="stylesheet" />
  </head>
  <body>
    <div id="map"></div>
    <form id="geocode-form">
      <input type="text" id="geocode-input" />
      <button type="submit">
        Geocode
      </button>
    </form>
  </body>
</html>

CSS

body {
  margin: 0;
  padding: 0;
}

#map {
  position: absolute;
  top: 0;
  bottom: 0;
  width: 100%;
}

#geocode-form {
  position: absolute;
  left: 20px;
  top: 20px;
  margin: 0;
  padding: 0;
}

JavaScript

// replace with your own API key
const API_KEY = 'eyJpIjoyNTcsImMiOjE2Njc0ODU2MjN9.c_UlvdpHGTI_Jb-TNMYlDYuIkCLJaUpi911RdlwPsAY';

/*
We create a map with initial coordinates zoom, a raster tile source and a layer using that source.
See https://maplibre.org/maplibre-gl-js-docs/example/map-tiles/
See https://maplibre.org/maplibre-gl-js-docs/style-spec/sources/#raster
See https://maplibre.org/maplibre-gl-js-docs/style-spec/layers/
*/
const map = new maplibregl.Map({
	container: 'map',
	center: [14.8981184, 49.8729317],
	zoom: 15,
	style: {
		version: 8,
		sources: {
			'basic-tiles': {
				type: 'raster',
				url: `https://api.mapy.cz/v1/maptiles/basic/tiles.json?apikey=${API_KEY}`,
				tileSize: 256,
			},
      'markers': {
				type: 'geojson',
				data: {
					type: 'FeatureCollection',
					features: [],
				},
				generateId: true,
			},
		},
		layers: [
    	{
        id: 'tiles',
        type: 'raster',
        source: 'basic-tiles',
      },
      {
      	id: 'markers',
        type: 'symbol',
        source: 'markers',
        layout: {
          'icon-image': 'marker-icon',
          'icon-size': window.devicePixelRatio > 1 ? 0.5 : 1,
          'icon-allow-overlap': true,
        },
        paint: {},
        filter: ['==', '$type', 'Point'],
      },
    ],
	},
});

/*
We also require you to include our logo somewhere over the map.
We create our own map control implementing a documented interface,
that shows a clickable logo.
See https://maplibre.org/maplibre-gl-js-docs/api/markers/#icontrol
*/
class LogoControl {
	onAdd(map) {
		this._map = map;
		this._container = document.createElement('div');
		this._container.className = 'maplibregl-ctrl';
		this._container.innerHTML = '<a href="http://mapy.cz/" target="_blank"><img  width="100px" src="https://api.mapy.cz/img/api/logo.svg" ></a>';

		return this._container;
	}
 
	onRemove() {
		this._container.parentNode.removeChild(this._container);
		this._map = undefined;
	}
}

// finally we add our LogoControl...