Okay, let's create a custom Leaflet control that includes an HTML input element (like a text box).
We'll achieve this by extending L.Control and implementing the onAdd method to create the necessary HTML elements using Leaflet's DOM utilities (L.DomUtil). We'll also add event listeners to handle input and prevent map interactions while typing.
Here's the breakdown:
- HTML Structure: A basic HTML page to host the map.
- CSS: Styling for the control to make it look like a standard Leaflet control and position the input correctly.
- JavaScript:
- Include Leaflet library.
- Create the map.
- Define the custom control class extending
L.Control.
- Implement
onAdd to build the control's DOM (div, label, input).
- Add event listeners to the input (e.g.,
input, keypress).
- Use
L.DomUtil and L.DomEvent for DOM manipulation and event handling within Leaflet's context.
- Prevent map interaction (dragging, scrolling) when interacting with the control/input.
- (Optional but recommended) Add a factory function for easier creation.
- Add the control to the map.
1. HTML (index.html):
<!DOCTYPE html>
<html>
<head>
<title>Leaflet Custom Control with Input</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"
integrity="sha200-ZcdRMZwOqUcdIQUtMJuWwG/PmEYmLcTvLZvEqIiDyZopwXjif6/IGZCHiginiG6r"
crossorigin=""/>
<style>
#map { height: 500px; width: 100%; }
/* Custom CSS for our control */
.leaflet-control.custom-input-control {
background-color: #fff;
padding: 6px 10px;
margin-right: 10px; /* Space from other controls */
box-shadow: 0 1px 5px rgba(0,0,0,0.65);
border-radius: 4px;
display: flex; /* Align label and input horizontally */
align-items: center; /* Vertically center items */
gap: 5px; /* Space between label and input */
color: #333;
font: 12px/1.5 "Helvetica Neue", Arial, Helvetica, sans-serif;
}
.leaflet-control.custom-input-control label {
white-space: nowrap; /* Prevent label wrapping */
}
.leaflet-control.custom-input-control input[type="text"] {
border: 1px solid #ccc;
padding: 4px;
border-radius: 3px;
font: inherit; /* Use same font as control */
outline: none; /* Remove default outline */
box-sizing: border-box; /* Include padding/border in width */
width: 150px; /* Adjust as needed */
}
/* Prevent Leaflet bar styling from interfering with the input's appearance */
.leaflet-control.custom-input-control .leaflet-bar a {
/* Remove default Leaflet bar link styles if they apply accidentally */
border: none;
background: none;
color: inherit;
text-decoration: none;
width: auto; /* Don't force standard bar item width */
height: auto; /* Don't force standard bar item height */
line-height: normal;
}
</style>
</head>
<body>
<div id="map"></div>
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"
integrity="sha200-aj9TaPshMztNCpsNVBMGrUbRfYzYxuLmm/Gmk3zQLtwOThof0GD0IygqA+wV"
crossorigin=""></script>
<script src="script.js"></script>
</body>
</html>
2. JavaScript (script.js):
// Define the custom control class
L.Control.Input = L.Control.extend({
// Default options
options: {
position: 'topleft', // Position on the map
placeholder: 'Enter search term...', // Placeholder for the input
labelText: 'Search:' // Text for the label
},
// Method called when the control is added to the map
onAdd: function (map) {
// Create the main container div for the control
// We use L.DomUtil.create to ensure compatibility with Leaflet's DOM handling
const container = L.DomUtil.create('div', 'leaflet-bar leaflet-control custom-input-control');
// Create the label
const label = L.DomUtil.create('label', '', container);
label.textContent = this.options.labelText;
// Create the input element
const input = L.DomUtil.create('input', 'custom-input', container);
input.type = 'text';
input.placeholder = this.options.placeholder;
// Store references to the elements for potential use in onRemove
this._container = container;
this._input = input;
// --- Prevent map interaction while interacting with the control/input ---
// Stop click events from propagating to the map (prevents map click handlers firing)
L.DomEvent.disableClickPropagation(container);
// Stop scroll events from propagating to the map (prevents map zoom)
L.DomEvent.disableScrollPropagation(container);
// Prevent the map from being dragged if a drag starts on the input
// This is especially important for touch devices
L.DomEvent.on(input, 'mousedown touchstart', L.DomEvent.stopPropagation);
// Alternatively, you could use L.DomEvent.disableMapDragging() on the input
// --- Add event listeners to the input ---
// Listen for input value changes (fires on every keypress, paste, etc.)
L.DomEvent.on(input, 'input', this._handleInput, this);
// Listen for the 'Enter' key press
L.DomEvent.on(input, 'keypress', this._handleKeyPress, this);
// Return the container element
return container;
},
// Method called when the control is removed from the map
onRemove: function (map) {
// Clean up event listeners to prevent memory leaks
if (this._input) {
L.DomEvent.off(this._input, 'input', this._handleInput, this);
L.DomEvent.off(this._input, 'keypress', this._handleKeyPress, this);
L.DomEvent.off(this._input, 'mousedown touchstart', L.DomEvent.stopPropagation);
}
if (this._container) {
L.DomEvent.off(this._container, 'click', L.DomEvent.disableClickPropagation); // Clean up propagation stopper if added
L.DomEvent.off(this._container, 'wheel', L.DomEvent.disableScrollPropagation); // Clean up propagation stopper if added
}
// Note: Leaflet's base L.Control handles removing the container element
// itself when onRemove finishes.
},
// --- Event handlers ---
_handleInput: function (e) {
const value = e.target.value;
console.log('Input value changed:', value);
// You could fire a custom event on the control here, e.g., this.fire('input', { value: value });
},
_handleKeyPress: function (e) {
// Check if the pressed key is 'Enter' (key code 13 for older browsers, 'Enter' for modern)
// Use e.originalEvent to access the native DOM event properties
if (e.originalEvent.key === 'Enter' || e.originalEvent.keyCode === 13) {
L.DomEvent.preventDefault(e); // Prevent default form submission if inside a form (though not in this case)
const value = e.target.value;
console.log('Enter pressed. Current value:', value);
// --- Do something with the input value ---
// Example: Trigger a search, update map view, etc.
alert('Searching for: ' + value); // Simple example action
// You could fire a custom event on the control here, e.g., this.fire('search', { value: value });
// Or call a method on the map instance passed to onAdd
// this._map.fireEvent('customsearch', { value: value });
}
},
// Public method to get the current value of the input
getValue: function() {
return this._input ? this._input.value : null;
},
// Public method to set the value of the input
setValue: function(value) {
if (this._input) {
this._input.value = value;
// Optionally fire an input event if setting programmatically should trigger handlers
// this._handleInput({ target: this._input });
}
}
});
// --- Factory function for easier creation ---
// This allows you to create the control like L.control.input({ ... })
L.control.input = function (options) {
return new L.Control.Input(options);
};
// --- Initialize the map and add the control ---
const map = L.map('map').setView([51.505, -0.09], 13);
L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 19,
attribution: '© <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
}).addTo(map);
// Add the custom input control to the map
const inputControl = L.control.input({
position: 'topright', // Example: place it on the top right
placeholder: 'Enter location...',
labelText: 'Go to:'
}).addTo(map);
// Optional: Listen to the 'enter' key press event if you decide to fire it within the control
// inputControl.on('search', function(e) {
// console.log('Control fired search event:', e.value);
// // Implement your search logic here
// });
// Example of getting the value externally
console.log('Initial input value:', inputControl.getValue());
Explanation:
L.Control.Input = L.Control.extend({...}): Defines a new class L.Control.Input that inherits from Leaflet's base L.Control class.
options: { ... }: Sets default options for the control. These can be overridden when creating an instance.
onAdd: function(map): This is the core method. Leaflet calls this when control.addTo(map) is executed.
L.DomUtil.create('div', 'leaflet-bar leaflet-control custom-input-control'): Creates the main div element for the control. We add standard Leaflet control classes (leaflet-bar, leaflet-control) and a custom class (custom-input-control) for specific styling.
L.DomUtil.create('label', '', container) and L.DomUtil.create('input', 'custom-input', container): Creates the label and input elements inside the container div.
this._container = container; this._input = input;: Stores references. Good practice for cleanup in onRemove.
- Preventing Map Interaction:
L.DomEvent.disableClickPropagation(container): Stops click events originating from within the control from reaching the map container. This prevents map click handlers (like placing a marker) from firing accidentally when clicking the control or input.
L.DomEvent.disableScrollPropagation(container): Stops mouse wheel/scroll events from zooming the map when scrolling over the control.
L.DomEvent.on(input, 'mousedown touchstart', L.DomEvent.stopPropagation): Specifically for the input field, this prevents Leaflet's map dragging from starting if the user tries to drag the map by clicking and dragging inside the input box.
- Adding Event Listeners:
L.DomEvent.on(input, 'input', this._handleInput, this): Attaches the _handleInput method to the input's input event. The last this ensures _handleInput runs in the context of the control instance.
L.DomEvent.on(input, 'keypress', this._handleKeyPress, this): Attaches _handleKeyPress to the keypress event, primarily to detect the 'Enter' key.
return container;: The onAdd method must return the main HTML element of the control.
Now, when you open index.html, you will see a text input box positioned on the map according to the specified position option. You can type into it, and check your browser's console for the log messages when the input changes or when you press Enter. The alert will also pop up when you press Enter.