You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何点击“显示我的位置”按钮后直接跳转至地图,无需点击链接?

Solution: Directly Jump to Map on Button Click

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 success function, we still generate the map URL the same way, but use window.open() to launch it immediately in a new tab (the _blank parameter ensures this behavior). Swap that line for window.location.href = mapUrl if you want the map to open in the same tab instead.
  • We removed all code that interacts with the mapLink element 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 18:42:34