如何实现地图缩放时保持地图标记固定在同一位置?
To keep your yellow marker (map pin) locked in the same relative position on the map—even when the map scales (like during zoom or container resizing)—we'll use CSS positioning to tie the marker directly to the map container. Here's how to adjust your code:
Step 1: Set Up the Container Positioning Context
First, update the .content-map container to act as a reference point for the marker. Add position: relative to its styles:
.content-map { float: left; width: 50%; padding-left: 2.5%; padding-right: 2.5%; position: relative; /* Critical: Makes child elements position relative to this container */ }
Step 2: Position the Marker Absolutely
Next, style the .content-map-items wrapper to place the marker exactly where you want it. We’ll use percentage values for top and left (so it scales with the map) and adjust alignment with transform to ensure the marker’s tip lands on your target point:
.content-map-items { position: absolute; /* Replace these percentages with your exact desired position */ top: 45%; /* Distance from the top of the map (tweak based on your map) */ left: 60%; /* Distance from the left of the map (tweak based on your map) */ /* Centers the marker's tip on the target point (adjust if your marker has a different shape) */ transform: translate(-50%, -100%); }
Why transform: translate(-50%, -100%)?
Most map pin images have their tip at the bottom center. This line shifts the marker left by 50% of its own width (so the center of the marker aligns with the left position) and up by 100% of its own height (so the bottom tip aligns with the top position). If your marker’s tip is in a different spot, adjust these values (e.g., translate(-50%, -50%) for a centered tip).
Step 3: Keep Marker Dimensions Fixed (Optional)
Ensure your marker image doesn’t scale with the map by keeping its width/height fixed. You can either keep the inline attributes or move them to CSS:
.fotoradar { width: 30px; height: 40px; /* Optional: Prevent unwanted scaling */ object-fit: contain; }
Final Code Example
Here’s your full code after the adjustments:
<style> .content-map { float: left; width: 50%; padding-left: 2.5%; padding-right: 2.5%; position: relative; } .content-map-items { position: absolute; top: 45%; left: 60%; transform: translate(-50%, -100%); } .fotoradar { width: 30px; height: 40px; } </style> <div class="content-map"> <img src="https://i.sstatic.net/icVEi.png" width="100%" /> <div class="content-map-items"> <img src="assets/img/fotoradar.png" class="fotoradar" /> </div> </div>
Just tweak the top and left percentages to match the exact spot on your map you want the marker to stay. Now when you zoom the page or resize the container, the marker will stick to that relative position perfectly!
内容的提问来源于stack exchange,提问作者Szymonex_

