Just Jolly Functions
Functions: Adding a Map with HTML, CSS, and JavaScript
Creating a Map Widget using HTML, CSS, and JavaScript can be done easily by integrating an API like Google Maps or Leaflet. This is a dynamic and interactive component that allows users to interact with a Google Map directly within a post page. Here's a detailed explanation of how it works, its features, and potential use cases:
Map Widget Overview:
The Map Widget is designed to:
Display a Google Map embedded on a webpage.
Allow users to search for locations via a search bar.
Let users place a marker on the map by clicking or dragging the marker.
Use Google Maps JavaScript API and Google Places API to interact with location data.
Use reverse geocoding to convert latitude and longitude into human-readable addresses.
Features of the Map Widget:
Interactive Map:
The map is rendered using the Google Maps JavaScript API, which provides an interactive interface for users to explore.
By default, the map is centered around New York City (lat: 40.730610, lng: -73.935242), but users can move the map to any location.
Search Box:
The search bar allows users to search for specific locations or places by name or address (e.g., "Eiffel Tower, Paris").
When a user enters a location in the search box, the map will automatically zoom into the location, and a marker will be placed at the address.
The search results are filtered using the Google Places API, which provides details about locations, landmarks, and places.
Marker Placement:
Users can place a marker on the map by clicking anywhere on the map, and the map will automatically adjust to center the marker.
The marker is draggable, meaning users can move the marker around the map to pinpoint a different location.
When the marker is moved, the map updates the corresponding address using reverse geocoding.
Reverse Geocoding:
Reverse geocoding is the process of converting geographic coordinates (latitude and longitude) into a human-readable address.
After placing the marker on the map (either by clicking or dragging), the widget will call the Google Geocoding API to fetch the address associated with the marker's location and update the input field accordingly.
Responsive Design:
The map widget is designed to take up the full height of the browser window (height: 100vh), ensuring a user-friendly experience across different screen sizes.
The search box is positioned above the map and is centered horizontally, making it accessible at all times.
Tip: Learn how to Insert HTML Code into Your Post.
Step 1: Create the HTML, CSS, and JavaScript for the Map Widget
We will use Google Maps API to embed a map into the page. First, you need to obtain an API key from Google Cloud Console.
Full Combined Code (HTML, CSS, JavaScript)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Map Widget</title>
<style>
body {
margin: 0;
font-family: Arial, sans-serif;
background-color: #f0f0f0;
}
.map-container {
position: relative;
width: 100%;
height: 100vh;
}
.search-box {
position: absolute;
top: 20px;
left: 50%;
transform: translateX(-50%);
background: #fff;
padding: 10px;
border-radius: 5px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
width: 300px;
z-index: 5;
}
.search-box input {
width: 100%;
padding: 8px;
border-radius: 4px;
border: 1px solid #ddd;
box-sizing: border-box;
}
</style>
</head>
<body>
<div class="map-container" id="map"></div>
<div class="search-box">
<input type="text" id="address" placeholder="Search for a place" />
</div>
<!-- Google Maps API Script -->
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_GOOGLE_MAPS_API_KEY&libraries=places&callback=initMap" async defer></script>
<script>
let map;
let marker;
let geocoder;
let searchBox;
// Initialize the map
function initMap() {
// Create a map centered at a default location
map = new google.maps.Map(document.getElementById("map"), {
center: { lat: 40.730610, lng: -73.935242 }, // Default location (New York)
zoom: 12,
});
// Create a marker
marker = new google.maps.Marker({
map: map,
draggable: true,
});
// Create geocoder to handle address input
geocoder = new google.maps.Geocoder();
// Create a search box for searching locations
searchBox = new google.maps.places.SearchBox(document.getElementById("address"));
// Bias the SearchBox results to the map's viewport
map.addListener("bounds_changed", () => {
searchBox.setBounds(map.getBounds());
});
// Event listener for SearchBox input change
searchBox.addListener("places_changed", () => {
const places = searchBox.getPlaces();
if (places.length === 0) return;
// Clear previous marker position
marker.setMap(null);
// Get the place and center the map
const place = places[0];
if (!place.geometry) return;
map.setCenter(place.geometry.location);
map.setZoom(14);
// Place a marker on the map
marker = new google.maps.Marker({
position: place.geometry.location,
map: map,
draggable: true,
});
// Update address input with the selected place's name
document.getElementById("address").value = place.name;
});
// Add listener to update marker position on map click
map.addListener("click", (e) => {
const latLng = e.latLng;
placeMarker(latLng);
});
// Add listener to update marker position on drag end
google.maps.event.addListener(marker, "dragend", function() {
const position = marker.getPosition();
updateAddress(position);
});
}
// Place marker on the map and update address input
function placeMarker(location) {
marker.setPosition(location);
map.panTo(location);
updateAddress(location);
}
// Reverse geocoding to get address from latitude and longitude
function updateAddress(latLng) {
geocoder.geocode({ location: latLng }, (results, status) => {
if (status === "OK" && results[0]) {
const address = results[0].formatted_address;
document.getElementById("address").value = address;
} else {
alert("Could not retrieve address");
}
});
}
</script>
</body>
</html>
Key Components Explained:
Google Maps API:
We load the Google Maps API using the <script> tag and pass in the YOUR_GOOGLE_MAPS_API_KEY. Replace this with your actual API key.
Map Initialization (initMap):
The map is initialized centered around a default location (New York City). The zoom level is set to 12.
Search Box (google.maps.places.SearchBox):
A search box allows users to search for places.
When the user types in an address, it updates the map view and places a marker at the searched location.
Marker:
A draggable marker is used to indicate the selected or clicked location on the map. The location of the marker is updated both when the user clicks on the map or when the marker is dragged.
Reverse Geocoding:
When the marker is moved or placed, the address is updated using Google Maps’ reverse geocoding feature.
CSS:
The CSS styles the map to take up the full height of the viewport and centers the search box at the top of the map.
How to Use:
Get a Google Maps API Key:
You need to obtain an API key from Google Cloud Console.
Enable the Google Maps JavaScript API and Places API.
Replace YOUR_GOOGLE_MAPS_API_KEY in the script tag with your actual key.
Run the code:
Simply open the index.html file in a web browser.
You should see the map with a search box. You can search for a location, click on the map, or drag the marker to update the location.
Summary
This map widget:
Displays a Google Map in a webpage.
Lets users search for places using the search box.
Allows placing and dragging a marker to update the location.
Uses Google Maps JavaScript API and Places API for location search and reverse geocoding.
This widget is simple and flexible, and it can be customized further to suit different needs (e.g., showing multiple markers, displaying information about the location, etc.).