Google Maps - Markers
Google Maps - Adding Markers
Section titled “Google Maps - Adding Markers”Markers are used to indicate specific locations on a map. They are a fundamental type of overlay, visually represented by an icon at a defined latitude and longitude.
This chapter covers how to add basic markers, customize their appearance and behavior, and manage them on the map.
Adding a Simple Marker
Section titled “Adding a Simple Marker”To add a marker, you first need to load the marker library and then instantiate the google.maps.Marker class (or the newer google.maps.marker.AdvancedMarkerView for more complex scenarios). You must provide at least the position and map properties.
- Import the Library: Add
markerto yourimportLibrarycall.
const { Map } = await google.maps.importLibrary("maps");const { Marker } = await google.maps.importLibrary("marker"); // <-- Add this- Create the Marker: Inside
initMap, after creating the map instance, create the marker.
const marker = new google.maps.Marker({ position: { lat: 17.3850, lng: 78.4867 }, // Hyderabad map: map, // Associate the marker with the 'map' instance title: 'Hyderabad, India' // Optional: Text tooltip on hover});Example: Adding a Marker to Hyderabad
Section titled “Example: Adding a Marker to Hyderabad”<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Simple Marker Map</title> <style>#map { height: 400px; width: 100%; } html, body { height: 100%; margin: 0; padding: 0; }</style></head><body> <div id="map"></div> <script> async function initMap() { const mapCenter = { lat: 17.3850, lng: 78.4867 }; // Hyderabad const { Map } = await google.maps.importLibrary("maps"); const { Marker } = await google.maps.importLibrary("marker"); // Import Marker class
const map = new Map(document.getElementById("map"), { zoom: 10, center: mapCenter, mapId: "DEMO_MAP_ID" });
// Create the marker const marker = new Marker({ position: mapCenter, // Place marker at the same center position map: map, title: 'Hyderabad' }); } </script> <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&v=weekly&libraries=marker" async defer></script> <!-- Note: Added &libraries=marker to the script URL --></body></html>Expected Output:
Section titled “Expected Output:”A map centered on Hyderabad with the default red Google Maps pin marker placed at the center. Hovering over the marker shows the tooltip ‘Hyderabad’.
Modern Alternative: AdvancedMarkerView
Section titled “Modern Alternative: AdvancedMarkerView”For enhanced performance, customization (including using HTML/CSS for the marker’s appearance), and accessibility, consider using AdvancedMarkerView. It requires importing the marker library.
const { AdvancedMarkerView } = await google.maps.importLibrary("marker");
const advancedMarker = new AdvancedMarkerView({ map: map, position: mapCenter, title: 'Hyderabad (Advanced)' // You can add custom HTML content here via the 'content' property});While Marker is simpler for basic use cases, AdvancedMarkerView is the recommended approach for new development, especially when dealing with many markers or complex styling. For the rest of this tutorial, we’ll stick to the basic Marker for simplicity, but be aware of this powerful alternative.
Animating Markers
Section titled “Animating Markers”You can add simple animations to Marker objects using the animation property. The two primary animations are:
google.maps.Animation.DROP: The marker appears to drop onto the map from above when added.google.maps.Animation.BOUNCE: The marker continuously bounces in place.
Set the animation property when creating the marker.
Example: Adding a Dropping Marker
Section titled “Example: Adding a Dropping Marker”<!DOCTYPE html><!-- ... (head section as before) ... --><body> <div id="map"></div> <script> async function initMap() { const mapCenter = { lat: 17.3850, lng: 78.4867 }; const { Map, Animation } = await google.maps.importLibrary("maps"); // Import Animation const { Marker } = await google.maps.importLibrary("marker");
const map = new Map(document.getElementById("map"), { zoom: 10, center: mapCenter, mapId: "DEMO_MAP_ID" });
const marker = new Marker({ position: mapCenter, map: map, title: 'Dropping Marker', animation: Animation.DROP // <-- Add animation property }); } </script> <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&v=weekly&libraries=marker,maps" async defer></script> <!-- Note: Added 'maps' library explicitly to ensure Animation enum is loaded --></body></html>Expected Output:
Section titled “Expected Output:”When the map loads, the marker will animate as if it’s dropping onto the specified location.
To make a marker bounce, change Animation.DROP to Animation.BOUNCE. To stop an animation programmatically, you can call marker.setAnimation(null);.
Customizing Markers
Section titled “Customizing Markers”You can change the default red pin to a custom image or use predefined vector symbols.
Using Custom Image Icons:
Section titled “Using Custom Image Icons:”Set the icon property to the URL of your image file. You can also provide a google.maps.Size object to specify the icon’s dimensions if needed, or a google.maps.Icon object for more control (size, origin, anchor).
const markerWithIcon = new google.maps.Marker({ position: { lat: 17.44, lng: 78.34 }, // Another location map: map, title: 'Custom Icon Marker', icon: 'https://maps.google.com/mapfiles/kml/shapes/info-i_maps.png' // Example URL /* // More advanced icon customization: icon: { url: 'path/to/your/custom-icon.png', scaledSize: new google.maps.Size(50, 50), // Display size in pixels origin: new google.maps.Point(0, 0), // Top-left corner of the sprite anchor: new google.maps.Point(25, 50) // Point on the icon to anchor to the lat/lng (e.g., bottom-center) } */});Using Vector Symbols:
Section titled “Using Vector Symbols:”Set the icon property to a google.maps.Symbol object literal. This is covered in more detail in the ‘Symbols’ chapter.
Making Markers Draggable:
Section titled “Making Markers Draggable:”Allow users to move a marker by setting draggable: true.
const draggableMarker = new google.maps.Marker({ position: { lat: 17.40, lng: 78.45 }, map: map, title: 'Drag Me!', draggable: true});
// You can listen for the 'dragend' event to get the new positiondraggableMarker.addListener('dragend', (event) => { const newPosition = event.latLng; console.log('Marker dragged to:', newPosition.lat(), newPosition.lng()); // Update database, etc.});Changing Marker Labels:
Section titled “Changing Marker Labels:”Add a single character label inside the default marker icon using the label property.
const labeledMarker = new google.maps.Marker({ position: { lat: 17.36, lng: 78.55 }, map: map, label: 'A', // Can be a string or a MarkerLabel object title: 'Marker A'});
/*// Using a MarkerLabel object for more control:const labeledMarkerB = new google.maps.Marker({ position: { lat: 17.37, lng: 78.56 }, map: map, label: { text: 'B', color: 'white', fontSize: '12px', fontWeight: 'bold' }, title: 'Marker B'});*/Removing Markers
Section titled “Removing Markers”To remove a marker from the map, call its setMap() method with null as the argument.
// Assuming 'marker' is a variable holding your Marker objectmarker.setMap(null);This doesn’t delete the marker object itself, just removes it from the display. You can add it back later by calling marker.setMap(map); again.
Example: Add and Remove Marker with Buttons (Conceptual)
Section titled “Example: Add and Remove Marker with Buttons (Conceptual)”Imagine you have HTML buttons to add/remove a marker:
<!-- HTML --><button id="addMarkerBtn">Add Marker</button><button id="removeMarkerBtn">Remove Marker</button><div id="map"></div>
<script> let map; let marker = null; // Keep track of the marker const markerPosition = { lat: 17.3850, lng: 78.4867 };
async function initMap() { const { Map } = await google.maps.importLibrary("maps"); const { Marker } = await google.maps.importLibrary("marker");
map = new Map(document.getElementById("map"), { /* ... map options ... */ });
document.getElementById('addMarkerBtn').addEventListener('click', () => { if (!marker) { // Only add if it doesn't exist marker = new Marker({ position: markerPosition, map: map, title: 'My Marker' }); } // Optionally bring it back if removed else if (marker.getMap() === null) { marker.setMap(map); } });
document.getElementById('removeMarkerBtn').addEventListener('click', () => { if (marker) { marker.setMap(null); } }); }</script><!-- API Script Load -->This example demonstrates the logic for dynamically adding and removing a marker based on user interaction.