如何点击“显示我的位置”按钮后直接跳转至地图,无需点击链接?
Got it, let's tweak your code so clicking the "Show my location" button takes you straight to the OpenStreetMap page with your location—no extra link click required. Here's how to make it happen:
1. Updated JavaScript Code
We'll adjust the success function to skip creating a visible link and instead directly launch the map URL right after getting your location. We can also remove all references to the mapLink element since we won't use it anymore.
function geoFindMe() { const status = document.querySelector('#status'); function success(position) { const latitude = position.coords.latitude; const longitude = position.coords.longitude; status.textContent = ''; // Build the map URL and open it in a new tab const mapUrl = `https://www.openstreetmap.org/#map=18/${latitude}/${longitude}`; window.open(mapUrl, '_blank'); // If you want to open the map in the same tab instead, use this line: // window.location.href = mapUrl; } function error() { status.textContent = 'Unable to retrieve your location'; } if(!navigator.geolocation) { status.textContent = 'Geolocation is not supported by your browser'; } else { status.textContent = 'Locating…'; navigator.geolocation.getCurrentPosition(success, error); } } document.querySelector('#find-me').addEventListener('click', geoFindMe);
2. Updated HTML Code
Since we don't need to display a link anymore, we can remove the <a id="map-link"> element. I also fixed a tiny typo in your viewport meta tag (it was missing scale=1.0):
<html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>Show My Location</title> </head> <body> <h1> TEST </h1> <p> Hello! </p> <button id="find-me">Show my location</button><br/> <p id="status"></p> </body> </html>
Quick Breakdown of Changes:
- In the
successfunction, we still generate the map URL the same way, but usewindow.open()to launch it immediately in a new tab (the_blankparameter ensures this behavior). Swap that line forwindow.location.href = mapUrlif you want the map to open in the same tab instead. - We removed all code that interacts with the
mapLinkelement because we no longer need to display a clickable link to the user. - Fixed the incomplete viewport meta tag to ensure proper mobile rendering.
内容的提问来源于stack exchange,提问作者Mohamad Sufian
相关产品推荐
相关产品推荐

